none
vb.net - serial port reading RRS feed

  • Question

  • Hi,

    I built a software that reads strings from serial port and store them in a multiline textbox.

    It works fine if software is running normally and multiline textbox stores them in multiline mode, but if I generate a "System.Threading.Thread.Sleep("17500")" to simulate a software lag, I get strings in continuous way, like a text and not in rows.

    I am using this code

     Private Sub ReceivedText(ByVal [text] As String)
            If Me.OutputTextBox.InvokeRequired Then
                Dim x As New SetTextCallBack(AddressOf ReceivedText)
                Me.Invoke(x, New Object() {(text)})
            Else
                If OutputTextBox.Text = "" Then
                    Me.OutputTextBox.Text &= [text] & vbCrLf
                Else
                    Me.OutputTextBox.AppendText([text] & vbCrLf)
                    'Me.OutputTextBox.Text &= [text] & vbCrLf
                End If
            End If
        End Sub

    to get data from serial port.

    Can anyone help me?

    Thanks

    Tuesday, June 4, 2019 7:55 AM

All replies

  • It seems you copied from somewhere code. 

    Here the same but more complete

    https://stackoverflow.com/questions/14226921/threading-copied-error-settextcallback


    Success
    Cor

    Tuesday, June 4, 2019 9:01 PM
  • I don't know what exactly you mean when you say "software lag" and if your application should become unresponsive for almost 20 seconds there is something wrong.

    When you open your serial port if data is being transmitted it will begin to fill the serial port read buffer, which has a default size of 4 KB, and the data will remain there until it is read. 

    So if you put a thread sleep of 17.5 seconds in your program and the baud rate is 9600 at the end of the 17.5 seconds there will be almost 17 KB of data in the read buffer in one continuous array. If you were to sleep too long the buffer would fill and "over run" corrupting the data and possibly crashing your app.

    Transmitting "Hello World" would fill the buffer like this Hello WorldHello WorldHello WorldHello WorldHello WorldHello WorldHello World.........etc

    How to get rows, well a good communications program will transmit and receive data with a defined protocol. For example one of the simplest protocols is to append a terminator to the string "Hello World"<LF> or perhaps "Hello World"<CR>. This would now fill the buffer like this "Hello World"<CR>"Hello World"<CR>"Hello World"<CR>"Hello World"<CR>"Hello World"<CR>.......etc , each string is now separated with a terminator and we can use the built in ReadLine method to pick out each individual string.

    Dim mystring=SerialPort1.ReadLine

    Wednesday, June 5, 2019 2:09 AM