

Serial communications can be done via either direct to physical serial port connected to the computer or via a USB to serial converter interface. For more information, see Statement.In today’s programming tutorial, I am going to describe some basics about how we can perform serial port communication from our C#.NET applications. This example uses a block to make sure that the application closes the port and to catch any timeout exceptions. For more information, see How to: Show Available Serial Ports.

For more flexibility, the code should allow the user to select the desired serial port from a list of available ports. This example assumes the computer is using COM1. In the code snippet picker, it is located in Connectivity and Networking. This code example is also available as an IntelliSense code snippet. ElseĮxample Function ReceiveSerialData() As Stringĭim com1 As IO.Ports.SerialPort = Nothing The block appends the string from the serial port to the return string. If Incoming Is Nothing ThenĪdd an Else block to the If statement to handle the case if the string is actually read. If it does return Nothing, exit the Do loop.

Use an If statement to determine if the ReadLine() method returns Nothing (which means no more text is available). Use the ReadLine() method to read the next available line of text from the serial port. ReturnStr = "Error: Serial Port read timed out."Ĭreate a Do loop for reading lines of text until no more lines are available. Dim com1 As IO.Ports.SerialPort = NothingĬom1 = My.("COM1") All code that manipulates the serial port should appear within this block. The block allows the application to close the serial port even if it generates an exception. For more information, see OpenSerialPort. Use the My. method to obtain a reference to the port. Dim returnStr As String = ""ĭetermine which serial port should provide the strings. This topic describes how to use My.Computer.Ports to receive strings from the computer's serial ports in Visual Basic.
