VB code to read data over a COM PORT that originates from an Arduino
The Arduino reads 8 Ultra-Sonic distance sensors and formats the sensor readings
as a line of text. The Arduino then executes a "Serial.Println" to sent the line of
text up the USB cable to a COM port on the PC. The PC is running a VB app that reads
the sensor values, and makes them available to other VB programs.
' The "VB Serial Port" object has code that runs for events that happen external to
' the Windows operating system. These events may be random with chaotic timing.
' So to run simultaneous with Windows, the serial port code cannot run in
' the same thread, as the VB code that updates the VB user interface.
' The "Serial Port" object just automatically runs in a separate thread.
' Code running on a separate thread cannot normally update code on a windows form.
' The method below named "AddToTextBox()" uses a DELEGATE to write the
' data from the com port to a text box on the windows form.
Private WithEvents MySerialPort As New Ports.SerialPort
Private Delegate Sub AddToTextBoxDelegate(sText As String)
' ------------------------------------------------------------------------------------------------
Private Sub SerialPortDataReceived(sender As Object, e As Ports.SerialDataReceivedEventArgs) _
Handles MySerialPort.DataReceived
' This event fires whenever the com port has received data
Dim DataReceived As String = MySerialPort.ReadLine
If mFormIsLargeSize Then
AddToTextBox(DataReceived)
End If
ProcessOneDataLine(DataReceived)
End Sub
Private Sub AddToTextBox(sText As String)
If txtDataFromComPort.InvokeRequired Then
' Caller was from a different thread
Dim del As New AddToTextBoxDelegate(AddressOf AddToTextBox)
txtDataFromComPort.Invoke(del, sText)
Else
' Caller was THIS thread
txtDataFromComPort.Text &= sText & vbCrLf
If txtDataFromComPort.Lines.Length > 20 Then txtDataFromComPort.Clear()
End If
End Sub
Private Sub ProcessOneDataLine(OneDataLine As String)
' 9/17/2020 - I modified the arduino program to put out only the 8 values
' seperated by commas. As a data confidence test, sText should contain 8 commas
' 8/6/2023 - Data line now looks like 22 8000, 24 8345 ...
Dim NbrOfSensors As Integer = 8
Dim PinNo As Integer
Dim Value As Integer
Dim PinOrValue() As String
If CommaCount(OneDataLine) = NbrOfSensors Then
Dim PinAndValues() As String = Split(OneDataLine, ",")
If PinAndValues.Length = NbrOfSensors + 1 Then
For Each Reading As String In PinAndValues
Reading = Reading.Trim
If Reading <> "" Then
PinOrValue = Split(Reading, " ")
PinNo = PinOrValue(0)
Value = PinOrValue(1)
mSensorValues(PinNo) = Value
End If
Next
Else
' Data has wrong number of values
' do nothing
End If
Else
' Data has wrong comma count
' do nothing
End If
End Sub