[英]Reading packet from serial port
我正在從串行端口讀取數據包。 數據包在數據包的開頭和結尾都有一個單字節的 0x7E 標志序列。 我正在使用此代碼從串行端口讀取數據包:
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));
}
}
我通常一次得到整個數據包。 問題是有時數據包被分解了。 這弄亂了我的整個代碼並破壞了它。 我想知道是否有一個簡單的解決方法?
由於我不知道您的代碼的 rest 我一起猜了一些東西,根據需要進行修改。 如果您已經使用了標志,為什么不使用它們呢?
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.