2013-08-05 33 views
0

我正在VB.NET中開發一個從SERIAL PORT讀取一些信息的項目。此信息包含4個字節。我能夠從串口讀取數據,但我得到的僅僅是4個數字。在VB.NET中使用字節

例如,我的讀數是:

134 0 0 4 
140 0 0 6 
141 0 0 5 
133 0 0 8 
... 

該手冊介紹如何這個數字轉換成可用的數據。我能夠做到這一點,但我不知道如何在VB.NET中編寫代碼。我不知道如何在字節級工作。

我附上一張關於字節含義的圖片。 enter image description here

+0

向我們展示你嘗試過什麼吧。 –

+1

我不想爲你寫代碼,所有我可以給你的是:http://www.tutorialspoint.com/vb.net/vb.net_bitshift_operators.htm這些都是vb.net中的位操作的所有操作符以一個很好的小例子 – x4rf41

+2

是的,我不想奴隸爲我工作:P。我正在尋找提示和教程。我將檢查該教程,看看我能否獲得一些有用的東西!謝謝! – Redder

回答

2

我得到了答案,這要歸功於用戶x4rf41

也許需要一些修正,但它是我一直在尋找。

這是代碼:

Private Sub thread_lectura_tarjeta1() 

     Dim RXByte As Byte 'byte recived 
     Dim RXPacket As List(Of Byte) = New List(Of Byte) 'each reading has 4 bytes 
     Dim lectura As Long = 0 'is the FINAL data 
     Dim COMPort As SerialPort = ensayo.get_digitalizadores(0).get_puerto_com 
     Dim chk_signo As Byte = 0 

     While (True) 

      lectura = 0 

      Do 'each package starts with a byte > 127, because is the only byte that its first bit is 0 

       RXByte = COMPort.ReadByte 

      Loop Until (RXByte > 127) 

      RXByte = RXByte And 127 
      RXPacket.Insert(0, RXByte) 

      RXByte = COMPort.ReadByte    
      RXPacket.Insert(1, RXByte) 

      RXByte = COMPort.ReadByte 
      chk_signo = RXByte And 8 
      RXPacket.Insert(2, RXByte And 7) 

      RXByte = COMPort.ReadByte 
      RXPacket.Insert(3, RXByte) 

      lectura = RXPacket.Item(0) + RXPacket.Item(1) * 128 + RXPacket.Item(2) * 16384 

      'checking sign 


      If chk_signo = 8 Then ' negative number 

       lectura = (lectura Xor 131071) * -1 
      End If 



      Sleep(1) 'wait 1 milisecond and read again 

     End While 
    End Sub