我正在编写一个 C# 应用程序,用于同时从多个串行 COM 端口读取数据,以分析 IPOD 的数据通信。发送的数据需要解释为十六进制字节。例如,
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 端口获取十六进制数据并根据命令头(0xFF 0x55)逐行显示它的最佳方法是什么。
有什么建议吗?
最佳答案
亚历克斯·法伯的方法很有效。下面是我的代码示例:
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) });
关于C#串口读取HEX数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21548828/