在C#中的串行端口读取 [英] Reading from the serial port in C#
问题描述
我一直在使用的Readline()和数据试过被丢弃,我尝试使用阅读(),但我不知道如何有这样做的一个错误的证明方法,因为我可能会得到几个包一个接一个,我没有明知有将是未来另一个数据包的方式,在数据包之间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.
我要指出,我没有得到任何保证,串脱落串口将\\\
或者终止\ R或\r\\\
。我只是需要一个傻瓜证明方法读取ALL当用户按下它打印将来自规模分组
I should mention that I get no guarantee that the string coming off the serial port will be ended with \n or \r or \r\n. 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
中的事件= http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.aspx> 的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#中的串行端口读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!