最近在使用 SerialPort 类发送串口数据,惊奇的发现PC端程序发送 0xFF 对面(ESP32)只能收到 0x7F。但是用串口工具是可以正常发送的。于是针对这个问题进行研究。Baidu上说是因为奇偶校验导致的,我设置了无校验现象依旧。
查看 SerialPort 类发现它有一个 Encoding 属性,默认是ASCIIEncoding,一般来说,正经的 ASCII 是 0-128 就是0-0x7F,因此,直觉上这个问题是它导致的。最终在下面的页面搜索到了答案:
http://www.innovatic.dk/knowledg/SerialCOM/SerialCOM.htm
By default, strings and char's are transmitted (not coded) as 7-bit ASCII where all characters above 127 are illegal and will be replaced with "?" (code 63) - even though you have defined 8 data bits! Therefore, you cannot use a string or char related method to send or read binary information (0-255) unless you change the encoding to something, which include all values up to 255 like:
YourSerialPort.Encoding = System.Text.Encoding.GetEncoding(28591) ' or YourSerialPort.Encoding = System.Text.Encoding.GetEncoding(1252)
于是按照上面的方法修改代码问题就得以解决。