【发布时间】:2011-10-28 21:47:58
【问题描述】:
我正在开发一个程序来与旧系统进行通信。我为此使用 System.IO.Ports.SerialPort。问题是当我发送更长的消息时,消息会损坏。我使用线路监听器并得到以下结果
我发送的内容
aa 01 00 00 12 03 06 18 02 c1 94 02 c1 94 00 00 00 00 00 00 00 00 00 00 00 00 1e fd
我得到了什么
c2 aa 01 00 00 12 03 06 18 02 c3 81 c2 94 02 c3 81 c2 94 00 00 00 00 00 00 00 00 00 00 00 00 1e c3 bd
我使用的代码是
_comPort.Encoding = new UTF8Encoding();
_comPort.PortName = PortName; //Com1
_comPort.BaudRate = BaudRate; //9600
_comPort.StopBits = StopBits; //1
_comPort.DataBits = DataBits; //8
_comPort.Parity = Parity; //None
_comPort.Open();
_comPort.Write(messageStr);
为什么数据会损坏,我该如何解决?
【问题讨论】:
-
不要将二进制数据存储在字符串中。 SerialPort.Write() 当你传递一个 byte[] 时,not 用 ascii 编码,字节不需要编码。
标签: c# serial-port communication