Reading from the serial port in C#(从 C# 中的串行端口读取)
问题描述
我尝试使用 Readline() 并且数据被丢弃,我尝试使用 Read() 但我不知道如何有一个错误证明方法来做到这一点,因为我可能会一个接一个地收到几个数据包而我没有知道会有另一个数据包进来的方法.在数据包之间BytesToRead是0,所以我不能使用它.当向缓冲区读取数据时,您有一个计时器或让线程休眠以允许所有数据包到达?
I have tried using Readline() and data gets dropped, I tried using Read() but I am not sure how to have an error proof method of doing it, since I may get several packets one after another and I have no way of knowing that there is going to be another packet coming in. In between packets BytesToRead is 0, so I can't use it. When reading data to the buffer to you have a timer or put the thread to sleep to allow for all the packets to arrive?
我迷路了.不知道下一步该尝试什么.
I am lost. Don't know what to try next.
我应该提一下,我不能保证从串行端口出来的字符串将以 或 或 结尾.我只需要一种万无一失的方法来读取用户按下 PRINT 时来自秤的所有数据包.
I should mention that I get no guarantee that the string coming off the serial port will be ended with or or . I simply need a fool proof way to read ALL the packets that will come from the scale when the user presses PRINT on it.
有人在这里回答了我喜欢的想法 - 为所有数据包等待一定的时间,但他们删除了他们的答案.你有机会重新发布吗?
Someone answered here with the idea I liked - waiting for a certain amount of time for all the packets, but they erased their answer. ANy chance you could re-post it?
推荐答案
你试过听DataRecieved
事件.io.ports.serialport.aspx" rel="noreferrer">SerialPort
类?
Have you tried listening to the DataRecieved
event of the SerialPort
class?
public class MySerialReader : IDisposable
{
private SerialPort serialPort;
private Queue<byte> recievedData = new Queue<byte>();
public MySerialReader()
{
serialPort = new SerialPort();
serialPort.Open();
serialPort.DataReceived += serialPort_DataReceived;
}
void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
{
byte[] data = new byte[serialPort.BytesToRead];
serialPort.Read(data, 0, data.Length);
data.ToList().ForEach(b => recievedData.Enqueue(b));
processData();
}
void processData()
{
// Determine if we have a "packet" in the queue
if (recievedData.Count > 50)
{
var packet = Enumerable.Range(0, 50).Select(i => recievedData.Dequeue());
}
}
public void Dispose()
{
if (serialPort != null)
serialPort.Dispose();
}
这篇关于从 C# 中的串行端口读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 C# 中的串行端口读取


- WebMatrix WebSecurity PasswordSalt 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01