reading data from a USB port using VB.net and Visual Studio Community - windows Forms application

Lloyd Linnell 1 Reputation point
2020-12-02T18:02:56.24+00:00

I need to read lines of data coming in on a USB port. I am using VB.net and Forms. In the toolbox, there is a 'SerialPort' control which I placed in my Form1.vb[Design] window. I am using the 'DataReceived' event and the event handler test code is:

Private Sub ttest(sender As Object, e As EventArgs) Handles SerialPort1.DataReceived
txtNext.Text = "x" ' simply writes an 'x' into a text box if the handler is called
End Sub

The event handler is never executed even though there is a constant arrival of lines of text on the serial port

Any suggestions?

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,569 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Xingyu Zhao-MSFT 5,356 Reputation points
    2020-12-07T05:52:43.75+00:00

    Hi @Lloyd Linnell ,

    Thank you for posting here.

    Here's an example of using serial port to receive data, and you can refer to it.

        Private isOpened As Boolean = False  
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  
            If Not isOpened Then  
                SerialPort1.PortName = "your port name"  
                SerialPort1.BaudRate = yourBaudRate  
      
                Try  
                    ' Open the serial port.  
                    SerialPort1.Open()  
                    isOpened = True  
                    AddHandler SerialPort1.DataReceived, AddressOf ttest_DataReceived  
                Catch  
                    MessageBox.Show("Failed to open serial port!")  
                End Try  
            Else  
      
                Try  
                    ' Close the serial port.  
                    SerialPort1.Close()  
                    isOpened = False  
                Catch  
                    MessageBox.Show("Failed to close the serial port!")  
                End Try  
            End If  
        End Sub  
      
        Private Sub ttest_DataReceived(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs)  
            txtNext.Text = "x"  
        End Sub  
    

    Hope it could be helpful.

    Besides, if the code cannot help you find the solution, please provide some related code about your question.

    Best Regards,
    Xingyu Zhao
    *
    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments