How to access serial ports by using Visual Basic 2005
Symptoms
For a Microsoft Visual Studio .NET version of this article, see 823179?(http://support.microsoft.com/kb/823179/).This step-by-step article describes how to access serial ports by using Microsoft Visual Basic 2005. This article also contains code examples that illustrate the concepts that are discussed.
Note You cannot use the Microsoft .NET Framework classes to directly access other types of ports, such as parallel ports or USB ports.
Resolution
To access serial ports by using Visual Basic 2005, follow these steps: Start Microsoft Visual Studio 2005.On the File menu, point to New, and then click Project.Under Project Types, expand Visual Basic, and then click Windows.Under Templates, click Console Application.In the Name box, type MyConsoleApplication, and then click OK.
By default, the Module1.vb file is created.To write data to a serial port, add the following SendSerialData method to the Module1.vb file.
Sub SendSerialData(ByVal data As String)’ Send strings to a serial port.Using com1 As IO.Ports.SerialPort = _My.Computer.Ports.OpenSerialPort(“COM1″)com1.WriteLine(data) com1.Close()End UsingEnd SubTo read data from a serial port, add the following ReceiveSerialData function to the Module1.vb file.
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″)DoDim Incoming As String = com1.ReadLine()If Incoming Is Nothing ThenExit DoElsereturnStr &= Incoming & vbCrLfEnd IfLoop com1.Close()End UsingReturn returnStrEnd FunctionTo read data from and write data to a serial port, add the following code to the Sub Main procedure.
Dim Data As StringData = “Test”Console.WriteLine(“Writing the following data to COM1: ” & Data)SendSerialData(Data)Console.WriteLine(“Read the following data from COM1: ” & ReceiveSerialData())Console.WriteLine(“Press ENTER to quit”)Console.ReadLine()To run the solution, press CTRL+F5.

Leave a Reply