[英]Reading packet from serial port
I'm reading a packet from a serial port.我正在从串行端口读取数据包。 The packet has a one byte 0x7E flag sequence at the beginning and end of the packet.
数据包在数据包的开头和结尾都有一个单字节的 0x7E 标志序列。 I'm using this code to read the packet from the serial port:
我正在使用此代码从串行端口读取数据包:
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (serialPort.BytesToRead > 0)
{
byte[] buffer = new byte[serialPort.BytesToRead];
int count = serialPort.Read(buffer, 0, serialPort.BytesToRead);
dataIN = ByteArrayToString(buffer);
this.Invoke(new EventHandler(DisplayData));
}
}
I usually get the whole packet all at once.我通常一次得到整个数据包。 The problem is sometimes the packet is broken up.
问题是有时数据包被分解了。 This messes up my whole code and breaks it.
这弄乱了我的整个代码并破坏了它。 I was wondering is there a easy fix for this?
我想知道是否有一个简单的解决方法?
Since I dont know the rest of your code I guessed something together, modify as needed.由于我不知道您的代码的 rest 我一起猜了一些东西,根据需要进行修改。 If you already employ flags, why not use them?
如果您已经使用了标志,为什么不使用它们呢?
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte lastByte = 0
ASCIIEncoding ascii = new ASCIIEncoding();
while (lastByte != 0x7E || serialPort.BytesToRead > 0)
{
int lastByte = serialPort.ReadByte()
if (lastByte != 0x7E)
dataIN += ascii.GetString(lastByte)
}
this.Invoke(new EventHandler(DisplayData));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.