C#Delphi ComPort通讯

时间:2011-04-25 22:53:38

标签: c# delphi

我使用Visual Studio 2008(C#)或Delphi CodeGear制作了与串口com端口设备通信的程序。 设备以十六进制格式向我发送数据并读取它。实例 - 40 32 00 D2 01 A6 B2 第一个字节“40”是设备的数量。 第二个字节“32”是按下设备的按钮。 等....

我的问题是如何分别查看字节。当我收到40 32 00 D2 01 A6 B2时 我不得不说这是设备'1'(例如),按下按钮'2'(例如)。 如果有人知道怎么做,我会非常感谢你的帮助。谢谢你

1 个答案:

答案 0 :(得分:0)

我找到了这段代码并使用它:

void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //determine the mode the user selected (binary/string)
            switch (CurrentTransmissionType)
            {
                //user chose string
                case TransmissionType.Text:
                    //read data waiting in the buffer
                    string msg = comPort.ReadExisting();
                    //display the data to the user
                    DisplayData(MessageType.Incoming, msg + "\n");
                    break;
                //user chose binary
                case TransmissionType.Hex:
                    //retrieve number of bytes in the buffer
                    int bytes = comPort.BytesToRead;
                    //create a byte array to hold the awaiting data
                    byte[] comBuffer = new byte[bytes];
                    //read the data and store it
                    comPort.Read(comBuffer, 0, bytes);
                    //display the data to the user
                    DisplayData(MessageType.Incoming, ByteToHex(comBuffer) + "\n");
                    break;
                default:
                    //read data waiting in the buffer
                    string str = comPort.ReadExisting();
                    //display the data to the user
                    DisplayData(MessageType.Incoming, str + "\n");
                    break;
            }
        }

我收到这个“40 32 00 D2 01 A6 B2”(HEX格式)我想第一个字节意味着这个设备是1号,第二个字节意味着按下按钮号N等.... .... / p>

相关问题