learning
Active member
I'm using the following to read a serial port. When run it displays the data correctly but stepping through the program I find that it loops through the serialdatarecieved event for each character of the port input rather than reading all of it. So _msg only equals one letter at a time. I'm trying to set a variable equal to the entire input stream but only get one character of it.
The end goal is to capture all of the data available on the port when the event triggers so that this data can then be processed. I tried using the bytestoread function, which gets the correct number of bytes to read, and then looped through to read a byte at a time but that didn't seem to work as I expected either. It just kept reading the first byte.
Any help you can offer would be appreciated.
Thanks
The end goal is to capture all of the data available on the port when the event triggers so that this data can then be processed. I tried using the bytestoread function, which gets the correct number of bytes to read, and then looped through to read a byte at a time but that didn't seem to work as I expected either. It just kept reading the first byte.
Any help you can offer would be appreciated.
Thanks
VB.NET:
Imports System.IO.Ports
Public Class CommTest
Dim WithEvents SerialPort As New SerialPort
Dim _msg As String
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If SerialPort.IsOpen Then
SerialPort.Close()
End If
Try
With SerialPort
.PortName = "COM1"
.BaudRate = 9600
.Parity = IO.Ports.Parity.None
.DataBits = 8
.StopBits = IO.Ports.StopBits.One
End With
SerialPort.Open()
lblMessage.Text = "COM1 Connected."
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived
_msg = SerialPort.ReadExisting
txtDataReceived.Invoke(New myDelegate(AddressOf updateTextBox))
End Sub
'------------------------------------------------------
' Delegate and subroutine to update the Textbox control
'------------------------------------------------------
Public Delegate Sub myDelegate()
Public Sub updateTextBox()
With txtDataReceived
.Font = New Font("Garamond", 12.0!, FontStyle.Bold)
.SelectionColor = Color.Red
.AppendText(_msg & vbCrLf)
.ScrollToCaret()
End With
End Sub
End Class