Simple Data Receiving.
The serial port can be used for simple text receiving with just a few lines of code. This example shows how to implement a receiving routine for a GPS device.
Create a form with a listbox (“lstPorts”), a textbox (“txtReceived”), a button (“btnStart”) and a serial port (“SerialPort1”). Adjust the textbox so that Multiline is True. Add the following code for the form load event to initialize the listbox with the available serial ports.
Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load For Each s In System.IO.Ports.SerialPort.GetPortNames() lstPorts.Items.Add(s) Next s End Sub
Add the following code for the btnStart Click command to initialize and open the serial port. Note that these values are appropriate for a standard GPS device. Your serial device may require different values.
Private Sub btnStart_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnStart.Click If lstPorts.SelectedIndex = -1 Then MsgBox("Please select a port") Exit Sub Else SerialPort1.BaudRate = 4800 SerialPort1.DataBits = 7 SerialPort1.Parity = IO.Ports.Parity.None SerialPort1.StopBits = IO.Ports.StopBits.One SerialPort1.PortName = lstPorts.SelectedItem.ToString SerialPort1.Open() Timer1.Start() End If End Sub
The serial port data received event runs on a different thread than the main GUI. Therefore it is not possible to directly update a GUI object (such as the litbox) from the serial port data received event. It must be done indirectly.
The easiest way to do this is via a data structure. The updating of this structure can be isolated from thread problems. The simplest structure to use is a queue – the data received event will add data to the queue, and a timer event in the main form will remove data from the queue.
Add a timer to the form and set the interval to 1000. Declare and initialise a queue object at the form level.
Dim Q As Queue(Of String) = New Queue(Of String)
In the data received event, add any data to the queue –
Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, _ ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) _ Handles SerialPort1.DataReceived Q.Enqueue(SerialPort1.ReadExisting()) End Sub
– and in the timer event, dequeue any items on the queue, and add them to the text box text. The dequeueing can be enclosed in a sync lock to avoid any possibility of threading issues.
Private Sub Timer1_Tick(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Timer1.Tick SyncLock Q While Q.Count > 0 txtReceived.Text &= Q.Dequeue End While End SyncLock End Sub
Finally, for safety, add a second button (btnStop) that will close the serial port and stop the timer before the form is closed.
Private Sub btnStop_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnStop.Click SerialPort1.Close() Timer1.Stop End Sub