应该收到的数据应该是“-31.12345 167.12345”,但有时我收到的数据如“2.378999E11 3.593719E”?我检查了我的端口设置他们使用相同的参数。我的代码如下:
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
byte rxChar=0;
byte[] rxDataBuffer = new byte[240];
int rxdata = 0;
rxNumberDataBytes = (byte)serialPort.BytesToRead;
//SerialPort sp = (SerialPort)sender;
//rxdata = sp.Read(rxDataBuffer, 0, 8);
while (serialPort.BytesToRead > 0)
{
rxChar = (byte)serialPort.ReadByte(); // read data
// to display bytes received in hex,check was all data received
Invoke(new Action(() =>
{
textBox3.Text += " " + rxChar.ToString("X") + "\r\n";
}));
switch (rxState)
{
case RxIdleState:
if (rxChar == 0x5A)
{
rxState = RxInstructionState;
}
break;
case RxInstructionState:
rxInstruction = rxChar;
rxState = RxNumberofbytesState;
break;
case RxNumberofbytesState:
rxChar = rxNumberDataBytes;
rxState = RxDataState;
rxdata = 0;
break;
case RxDataState:
// count number of rxdata until 8 bytes real data
rxDataBuffer[rxdata] = rxChar;
rxdata++;
if (rxdata == 8)
{
float f11 = BitConverter.ToSingle(rxDataBuffer, 0);
float f22 = BitConverter.ToSingle(rxDataBuffer, 4);
Invoke(new Action(() =>
{
textBox3.Text += f11.ToString() + " " + f22.ToString() + "\r\n";
}));
rxState = RxStopState;
}
break;
case RxStopState:
if (rxChar == 0x2C)
{
rxState = RxIdleState;
}
break;
default:
rxState = RxIdleState;
break;
}
}
}
}
答案 0 :(得分:0)
我认为由于错误的设置操作,您正在抓取错误的数据。
在下文中,您将设置所需的字节数,然后将rxChar
设置为流中的第一个可用字节。这看起来很好。
rxNumberDataBytes = (byte)serialPort.BytesToRead;
while (serialPort.BytesToRead > 0)
{
rxChar = (byte)serialPort.ReadByte(); // read data
....
}
但是,在下文中,您将忽略该rxChar
值并将其设置为可供读取的字节数。
case RxNumberofbytesState:
rxChar = rxNumberDataBytes; // <--- This is correct?
rxState = RxDataState;
rxdata = 0;
break;
然后,您使用新的rxChar
值添加到rxDataBuffer
,而不是串行端口中可用的第一个字节。
查看代码的流程,7个字节的其余部分看起来都是正确的,但第一个字节总是错误的。
也可能只是浮点精度问题;)