2011-04-25 69 views
2

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

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

+2

你说你”读它“。你怎么读它(以什么格式 - 字符串,字节数组,??)? – 2011-04-25 23:16:06

+2

您可以发布一些代码(只是读取传入数据的部分)。 – ChrisWue 2011-04-25 23:26:16

回答

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 01 D2 A6 B2 “(十六进制格式)我想第一个字节意味着这个设备是第一个,第二个字节意味着按钮编号N被按下等等... ...

+0

对不起,但我不知道如何在这里格式化代码。 – user724468 2011-04-26 11:09:45

+0

选择代码,按编辑器上方的“{}”按钮或“Ctrl + K”。 – 2011-04-26 11:42:21

+0

或者:'

your block of code
'。 – 2011-04-26 11:43:27