1

c# SerialPort HEX there is no data received - Dolen

 1 year ago
source link: https://www.cnblogs.com/sayshap/p/16468077.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

c# SerialPort HEX there is no data received

C#窗口程序进行串口通信,按照串口通信协议,设置com口,波特率,停止位,校验位,数据位,本地虚拟串口调试ok,但是和外设调试时,发送HEX模式数据命令,没有数据返回,

所以关键问题在于HEX模式,发送命令格式也必须是HEX模式下,废话不多说,上代码:

        public byte[] HexStringToBytes(string hs)
        {
            string[] strArr = hs.Trim().Split(' ');
            byte[] b = new byte[strArr.Length];
            //逐个字符变为16进制字节数据
            for (int i = 0; i < strArr.Length; i++)
            {
                b[i] = (byte)int.Parse(strArr[i], System.Globalization.NumberStyles.HexNumber);
            }
            //按照指定编码将字节数组变为字符串
            return b;
        }

关键代码:

int.Parse(strArr[i], System.Globalization.NumberStyles.HexNumber);

之前无论如何也无法接收到数据,通过此段代码轻松解决HEX模式无响应值的问题。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK