Csharp/C#教程:C#串口读取HEX数据分享


C#串口读取HEX数据

我正在编写一个C#应用程序,同时从多个串行COM端口读取数据,以分析IPOD的数据通信。 发送的数据需要解释为HEX字节。 例如,

0xFF 0x55 0x01 0x00 0x04 0xC3 0xFF 0x55 …

我希望能够阅读此内容并将其显示在富文本框中

0xFF 0x55 0x01 0x00 0x04 0xC3 0xFF 0x55 ... 

命令的开头包括一个标题(0xFF 0x55),其余的是命令+参数+校验和。

最好的方法是什么?

我目前有:

 private delegate void SetTextDeleg(string text); void sp_DataReceivedRx(object sender, SerialDataReceivedEventArgs e) { Thread.Sleep(500); try { string data = IPODRxPort.ReadExisting(); // Is this appropriate?? // Invokes the delegate on the UI thread, and sends the data that was received to the invoked method. // ---- The "si_DataReceived" method will be executed on the UI thread which allows populating of the textbox. this.BeginInvoke(new SetTextDeleg(si_DataReceivedRx), new object[] { data }); } catch { } } private void si_DataReceivedRx(string data) { int dataLength = data.Length*2; double numLines = dataLength / 16.0; for (int i = 0; i < numLines; ++i) IPODTx_rtxtBox.Text += "n"; IPODRx_rtxtBox.Text += SpliceText(convertAsciiTextToHex(data), 32) + "n"; } 

我可以读取数据,但它的格式不合适。

我只是不确定从com端口获取hex数据的最佳方法是什么,并根据命令头(0xFF 0x55)逐行显示它。

有什么建议?

亚历克斯法伯的方法有效。 下面是我的代码示例:

上述就是C#学习教程:C#串口读取HEX数据分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 SerialPort sp = (SerialPort) sender; // string s = sp.ReadExisting(); // labelSerialMessage.Invoke(this.showSerialPortDelegate, new object[] { s }); int length = sp.BytesToRead; byte[] buf = new byte[length]; sp.Read(buf, 0, length); System.Diagnostics.Debug.WriteLine("Received Data:" + buf); labelSerialMessage.Invoke(this.showSerialPortDelegate, new object[] { System.Text.Encoding.Default.GetString(buf, 0, buf.Length) }); 

www.ctvol.com true Article Csharp/C#教程:C#串口读取HEX数据分享

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1020418.html

(0)
上一篇 2022年1月5日 上午5:00
下一篇 2022年1月5日 上午5:01

精彩推荐