| title | How to: Receive Strings From Serial Ports in Visual Basic | |||
|---|---|---|---|---|
| ms.custom | ||||
| ms.date | 07/20/2015 | |||
| ms.prod | .net | |||
| ms.reviewer | ||||
| ms.suite | ||||
| ms.technology |
|
|||
| ms.topic | article | |||
| helpviewer_keywords |
|
|||
| ms.assetid | 8371ce2c-e1c7-476b-a86d-9afc2614b6b7 | |||
| caps.latest.revision | 21 | |||
| author | dotnet-bot | |||
| ms.author | dotnetcontent |
This topic describes how to use My.Computer.Ports to receive strings from the computer's serial ports in [!INCLUDEvbprvb].
-
Initialize the return string.
[!code-vbVbVbalrMyComputer#38]
-
Determine which serial port should provide the strings. This example assumes it is
COM1. -
Use the
My.Computer.Ports.OpenSerialPortmethod to obtain a reference to the port. For more information, see xref:Microsoft.VisualBasic.Devices.Ports.OpenSerialPort%2A.The
Try...Catch...Finallyblock 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.[!code-vbVbVbalrMyComputer#39]
-
Create a
Doloop for reading lines of text until no more lines are available.[!code-vbVbVbalrMyComputer#40]
-
Use the xref:System.IO.Ports.SerialPort.ReadLine method to read the next available line of text from the serial port.
[!code-vbVbVbalrMyComputer#41]
-
Use an
Ifstatement to determine if the xref:System.IO.Ports.SerialPort.ReadLine method returnsNothing(which means no more text is available). If it does returnNothing, exit theDoloop.[!code-vbVbVbalrMyComputer#42]
-
Add an
Elseblock to theIfstatement to handle the case if the string is actually read. The block appends the string from the serial port to the return string.[!code-vbVbVbalrMyComputer#43]
-
Return the string.
[!code-vbVbVbalrMyComputer#44]
[!code-vbVbVbalrMyComputer#37]
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 Code Snippets.
This example assumes the computer is using COM1.
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.
This example uses a Try...Catch...Finally block to make sure that the application closes the port and to catch any timeout exceptions. For more information, see Try...Catch...Finally Statement.
xref:Microsoft.VisualBasic.Devices.Ports
xref:System.IO.Ports.SerialPort?displayProperty=nameWithType
How to: Dial Modems Attached to Serial Ports
How to: Send Strings to Serial Ports
How to: Show Available Serial Ports