C#串行端口读取十六进制数据

C#串行端口读取十六进制数据,c#,hex,uart,C#,Hex,Uart,我正在编写一个C#应用程序,同时从几个串行COM端口读取数据,以分析IPOD的数据通信。发送的数据需要解释为十六进制字节。比如说, 0xFF 0x55 0x01 0x00 0x04 0xC3 0xFF 0x55 例如,我希望能够阅读并在富文本框中显示它 0xFF 0x55 0x01 0x00 0x04 0xC3 0xFF 0x55 ... 命令的开头包括一个标头(0xFF 0x55),其余的是命令+参数+校验和 最好的办法是什么 我目前有: private delegate void Set

我正在编写一个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"; 
}
private delegate void SetTextDeleg(字符串文本);
void sp_DataReceivedRx(对象发送方,SerialDataReceivedEventArgs e)
{
睡眠(500);
尝试
{
string data=ipodxport.ReadExisting();//这是否合适??
//在UI线程上调用委托,并将接收到的数据发送到调用的方法。
//---“si_DataReceived”方法将在允许填充文本框的UI线程上执行。
this.BeginInvoke(新的SetTextDeleg(si_DataReceivedRx),新的对象[]{data});
}
抓住
{ }
}
私有void si_DataReceivedRx(字符串数据)
{
int dataLength=data.Length*2;
双数字线=数据长度/16.0;
对于(int i=0;i
我可以读取数据,但格式不正确

我只是不确定从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) });

使用
Read(byte[]buffer,int offset,int count)
函数代替
ReadExisting
,因为通信协议不是基于文本的。在之前调用
BytesToRead
属性,以检测所需的数组大小。您尚未关闭。您需要更好地描述消息格式,“ipod”并不是一个很好的选择器。