Search code examples
wpfvb.netsynchronizationreal-time

Receive data from serialport in realtime VB.net


I created this code to receive data from serial port (com)

 Private port As New SerialPort("COM1", 9600, Parity.None, 8, StopBits.One)

Function ReceiveSerialData() As String

    Dim returnStr As String = ""

    Dim com1 As IO.Ports.SerialPort = Nothing
    Try

        port.Open()

        port.ReadTimeout = 1000

        Dim Incoming As String

            Incoming = port.ReadLine()

        returnStr = Incoming

    Catch erreur As IOException
        returnStr = "Check Port"
    Catch ex As TimeoutException
        returnStr = "Error: Serial Port read timed out."
    Finally
        If port IsNot Nothing Then port.Close()
    End Try

    Return returnStr
End Function



Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded

    Label2.Content = ReceiveSerialData()

End Sub

I want to create an event to re execute this code when the data's changed in real time.

My Form is like this : enter image description here

Any suggestion ?


Solution

  • Well, you can always go with some form of the Do While True mentioned in the comments. Not ideal but...

    This is a modified version of your code, to include the reading part in a different thread. When it reads something, it raises an event you can subscribe to (or you could simply put the text in your control directly after reading). The port stays open all the time, so in this example it is being closed when the form is closed.

    Try it and see if it works for you.

    Private port As New SerialPort("COM1", 9600, Parity.None, 8, StopBits.One)
    Private rdthread As System.Threading.Thread
    Event PortData(ByVal Message as String)
    
    Private Sub readPort()
        Do While True
            Try
                Dim message As String = port.ReadLine()
                RaiseEvent PortData(message)
                System.Threading.Thread.Sleep(0)
                My.Application.DoEvents()
            Catch ex As Exception
                Exit Do
            End Try
        Loop
    End Sub    
    
    Private Sub HandleData(ByVal message as string) Handles Me.PortData
        Label2.Content = message
    End Sub
    
    Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
        InitPort()
    End Sub
    
    Private Sub Window_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Try
            If port.IsOpen Then port.Close()
        Finally
            port.Dispose()
        End Try
    End Sub 
    
    Sub InitPort() 
        Dim com1 As IO.Ports.SerialPort = Nothing
        Try
            port.Open()
            port.ReadTimeout = 1000
    
            rdthread = New System.Threading.Thread(AddressOf readPort)
            rdthread.Start()
    
        Catch erreur As IOException
            returnStr = "Check Port"
        Catch ex As TimeoutException
            returnStr = "Error: Serial Port read timed out."
        Catch ex as Exception
    
        End Try
    End Sub