我正在开发一个 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 通信时,我确实得到了响应,所以我认为设备的响应没有问题。我在串行通信方面做错了什么?任何帮助将非常感激。