作者:我女神不能F哭不能输丶 | 来源:互联网 | 2023-09-09 15:32
C#串口读取HEX数据我正在编写一个C#应用程序,同时从多个串行COM端口读取数据,以分析IPOD的数据通信。发送的数据需要解释为HEX字节。例如,0xFF0x550x010x00
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
我可以读取数据,但它的格式不合适。
我只是不确定从com端口获取hex数据的最佳方法是什么,并根据命令头(0xFF 0x55)逐行显示它。
有什么建议?
亚历克斯法伯的方法有效。 下面是我的代码示例:
上述就是C#学习教程:C#串口读取HEX数据分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—编程笔记
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) });