我的项目中有一个Modbus接口。我的PC上有两个串口,一个在板上,一个在USB到串口。 如果我使用板载串口,我总是会错过返回字符串的最后一个字符,如果我使用USB转串口,我总是得到整个返回字符串。
// ONBOARD --------
TX:01 03 02 00 00 12 C4 7F
RX:01 03 24 00 00 00 64 00 00 00 0C 00 00 00 00 06 FA 02 D0 D9 54 00 00 00 00 00 04 00 0C 00 00 00 0C 00 00 00 00 00 00 C6
// USB to SERIAL --------------
TX:01 03 02 00 00 12 C4 7F
RX:01 03 24 00 00 00 64 00 00 00 0C 00 00 00 00 06 FA 02 D0 D9 54 00 00 00 00 00 04 00 0C 00 00 00 0C 00 00 00 00 00 00 C6 E9
如果使用DataReceivedHandler事件:
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
int rxcnt = 0;
SerialPort sp = (SerialPort)sender;
for (rxcnt = 0; rxcnt < _serialPort.BytesToRead; rxcnt++)
{
rx_buffer[rx_buffer_len++] = (Byte)_serialPort.ReadByte();
}
}
相同的代码在2个不同的端口上运行,但结果不同,有什么想法? 问候 理查德
我刚发现的东西......我冲进了in&amp;在发送Modbus消息之前输出缓冲区。 如果我不刷新rx_buffer,我会在下一个收到的数据包的开头看到丢失的字符: TX:01 03 02 00 00 12 C4 7F RX:01 03 24 00 00 00 64 00 00 00 0C 00 00 00 00 06 FA 02 D0 D9 54 00 00 00 00 00 04 00 0C 00 00 00 0C 00 00 00 00 00 00 C6
TX:01 03 02 00 00 12 C4 7F RX: E9 01 03 24 00 00 00 00 00 00 00 0 00 00 00 00 06 FA 02 D0 D9 54 00 00 00 00 00 04 00 0C 00 00 00 0C 00 00 00 00 00 00 C6
我不明白为什么这个字符会出现下一条消息,因为两条消息之间有1000mS的延迟
_serialPort = new SerialPort();
_serialPort.PortName = ports.ElementAt(0);
_serialPort.BaudRate = 9600;
_serialPort.Parity = Parity.None;
_serialPort.DataBits = 8;
_serialPort.StopBits = StopBits.One;
_serialPort.Handshake = Handshake.None;
_serialPort.ReadBufferSize = 250;
_serialPort.ReceivedBytesThreshold = 1;
_serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
try
{
_serialPort.Open();
}
catch
{
this.Close();
}