【发布时间】:2021-09-13 23:57:16
【问题描述】:
我正在开发一个 C# 应用程序。我的应用程序必须与硬件设备进行串行通信。该设备通过“COM4”com 端口与我的系统连接。代码:
serialPort = new SerialPort("COM4", 2400, Parity.Odd, 8, StopBits.One);
serialPort.WriteTimeout = 5000;
serialPort.ReadTimeout = 5000;
serialPort.Open();
serialPort.Handshake = Handshake.None;
serialPort.DtrEnable = true;
serialPort.RtsEnable = true;
之后我做了一个写操作,这工作正常。代码:
private void WriteMessage(byte[] busMsg)
{
BinaryWriter writer = new BinaryWriter(serialPort.BaseStream);
writer.Write(busMsg);
writer.Flush();
}
写入后,当我执行 ReadByte 操作时,我得到超时异常。代码:
private byte ReadAEBusMessageResponse()
{
BinaryReader reader = new BinaryReader(serialPort.BaseStream);
return reader.ReadByte();
}
我在谷歌某处读到 BaseStream 可能会导致问题,所以我尝试了以下代码进行阅读,但仍然没有运气,我仍然收到超时异常。
private byte ReadAEBusMessageResponse()
{
SerialPort currentPort = serialPort;
return Convert.ToByte(currentPort.ReadByte());
}
当我尝试与 Hercules 通信时,我确实得到了响应,所以我认为设备的响应没有问题。我在串行通信方面做错了什么?任何帮助将不胜感激。
【问题讨论】:
-
"写完后,当我做ReadByte操作"不写直接读,结果会不一样?
-
让我检查一下,但我必须写,因为这是我发送给设备的命令,设备根据该命令响应
-
@LouisGo 仍然出现超时异常,这很明显
-
设备可能没有真正从系统得到消息,因此没有回复(字节)可读取。写完之后检查
SerialPort.BytesToRead可能会有所帮助。如果您的设备能够显示收到的消息,这将有很大帮助。 -
在“SerialPort.BytesToRead”中得到 0。该设备是真正的硬件设备,因此无法显示其接收到的消息。 @LouisGo
标签: c# serial-port .net-core-3.1