Quantcast
Channel: VBForums - Visual Basic .NET
Viewing all articles
Browse latest Browse all 27554

Serial port DataReceived event not getting all data

$
0
0
Hi all!

I am using the serial.datareceived event to call a sub and display the data in a rich textbox. It all works great when I run the app. The problem is that I want to get certain data out of the entire data sent, i.e. - the number values and not the words. When I step thru the program I notice that the .text value is received in multiple runs of the displaying sub. It is not receiving the entire thing in one read and that makes my text.length values incorrect because they are changing until the entire data package is read. I am using serialport1.readexisting() to get the data. How can I make sure that all of the data is received before I try to get its length? Here is the code. Ignore threading issues for now unless they are glaring and obvious.

Code:

Imports System
Imports System.IO.Ports
Public Class frm_BeerScale

    Delegate Sub NumberCallBack(ByVal number As Integer)
    Delegate Sub TextCallBack(ByVal text As String)


    Private Sub BeerScale_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        SerialPort1.PortName = "COM6"
        If Not SerialPort1.IsOpen Then
            SerialPort1.Open()
        End If

    End Sub

    Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived

        ReceivedText(SerialPort1.ReadExisting())

    End Sub

    Private Sub ReceivedText(ByVal text As String)

        Dim test As Integer
        If Me.rtbx_Data.InvokeRequired Then
            Dim x As New TextCallBack(AddressOf ReceivedText)
            Me.Invoke(x, text)
        Else
            Me.rtbx_Data.Text &= text
        End If
        test = text.Length
        ChangeLabel(test)

        'If Me.lbl_serialBeerWeight.InvokeRequired Then
        '    Dim x As New TextCallBack(AddressOf ReceivedText)
        '    Me.Invoke(x, text)
        'Else
        '    Me.lbl_serialBeerWeight.Text = test
        'End If

    End Sub

    Private Sub btn_close_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_close.Click

        If SerialPort1.IsOpen Then
            SerialPort1.Close()
            Me.Close()
        Else
            Me.Close()
        End If

    End Sub

    Private Sub ChangeLabel(ByVal number As Integer)

        If Me.lbl_serialBeerWeight.InvokeRequired Then
            Dim x As New NumberCallBack(AddressOf ChangeLabel)
            Me.Invoke(x, number)
        Else
            Me.lbl_serialBeerWeight.Text = number
        End If
    End Sub
End Class


Any help is appreciated.

Tom

Viewing all articles
Browse latest Browse all 27554

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>