Binary Data

Binary Data

Receiving binary data at the serial port is slightly  different than receving text, because you must treat it as an array of bytes.   This example shows how to do that, together with a simple way to display the  data.

If your serial device is transmitting binary data then  it is critically important that you do not attempt to process that data as a  string at any point of the process.  Any time data receved at the serial  port is converted to a string, the system will apply a conversion from a single  byte to a multi-byte text character.  This  conversion will change your data, making subsequent  processing incorrect.  If data being received is not text with a known  encoding format (eg, ASCII) then it must be received as binary data – an array  of byes.

The example below shows how to receive data into an array of  bytes.  The example also shows a simple way to work around the problem that  the serial port runs on a different thread than the one used for the GUI.   It uses a queue to transfer the data from the data received event to the GUI  proessing, and uses a timer (which runs in the GUI thread) to retrieve the data  from the queue.  The SyncLock is used to ensure there is no conflict  between the two threads (although it is probably not needed, as there is only  one enqueueing and only one dequeueing). The displayed data is displayed as hex  in a text box.

Public Class  Form1

Dim q As Queue

Private Sub SerialPort1_DataReceived(ByVal sender As  System.Object, _
    ByVal e As  System.IO.Ports.SerialDataReceivedEventArgs) _
    Handles SerialPort1.DataReceived
  While SerialPort1.BytesToRead > 0
  End While
End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles  Timer1.Tick
  SyncLock q
  While q.Count > 0
    Dim B As Byte = q.Dequeue
    TextBox1.Text &= Hex(B) & " "
  End While
  End SyncLock
End Sub

End Class
  1. #1 by John Doe on September 25, 2016 - 9:01 pm

    how do i then alter the code on the other 2 webpages (“Simple Data Receiving” and “Receiving Text with a Delegate”) to send data as hex?

    • #2 by vbdotnetblogg on September 27, 2016 - 9:09 pm

      Both those examples refer to receiving data and cannot be modified to send data. The MS documentation has examples for sending data. Please note that data is not likely to be sent as hex – hex is simply a way of representing byte values for display and is not appropriate for serial data communication. Questions related to sending data should be asked in the VB forum.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s