How to: Receive Strings From Serial Ports in Visual Basic
This topic describes how to use My.Computer.Ports to receive strings from the computer's serial ports in Visual Basic.
To receive strings from the serial port
Initialize the return string.
Dim returnStr As String = ""
Determine which serial port should provide the strings. This example assumes it is COM1.
Use the My.Computer.Ports.OpenSerialPort method to obtain a reference to the port. For more information, see My.Computer.Ports.OpenSerialPort Method.
The Using block allows the application to close the serial port even if it generates an exception. All code that manipulates the serial port should appear within this block, or within a Try...Catch...Finally block.
Using com1 As IO.Ports.SerialPort = _ My.Computer.Ports.OpenSerialPort("COM1") End Using
Create a Do loop for reading lines of text until no more lines are available.
Do Loop
Use the ReadLine method to read the next available line of text from the serial port.
Dim Incoming As String = com1.ReadLine()
Use an If statement to determine if the ReadLine method returns Nothing (which means no more text is available). If it does return Nothing, exit the Do loop.
If Incoming Is Nothing Then Exit Do End If
Add an Else block to the If statement to handle the case if the string is actually read. The block appends the string from the serial port to the return string.
Else returnStr &= Incoming & vbCrLf
Return the string.
Return returnStr
Example
Function ReceiveSerialData() As String
' Receive strings from a serial port.
Dim returnStr As String = ""
Using com1 As IO.Ports.SerialPort = _
My.Computer.Ports.OpenSerialPort("COM1")
Do
Dim Incoming As String = com1.ReadLine()
If Incoming Is Nothing Then
Exit Do
Else
returnStr &= Incoming & vbCrLf
End If
Loop
End Using
Return returnStr
End Function
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Connectivity and Networking. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Compiling the Code
This example assumes the computer is using COM1.
Robust Programming
This example assumes the computer is using COM1. For more flexibility, the code should allow the user to select the desired serial port from a list of available ports. For more information, see How to: Show Available Serial Ports in Visual Basic.
This example uses a Using block to make sure that the application closes the port even if it throws an exception. For more information, see Using Statement (Visual Basic).
See Also
Tasks
How to: Dial Modems Attached to Serial Ports in Visual Basic
How to: Send Strings to Serial Ports in Visual Basic
How to: Show Available Serial Ports in Visual Basic