Microsoft KB Archive/904795

= How to access serial ports by using Visual Basic 2005 =

Article ID: 904795

Article Last Modified on 12/6/2006

-

APPLIES TO


 * Microsoft Visual Studio 2005 Standard Edition
 * Microsoft Visual Studio 2005 Professional Edition
 * Microsoft Visual Basic 2005

-





INTRODUCTION


For a Microsoft Visual Studio .NET version of this article, see 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.



MORE INFORMATION
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(&quot;COM1&quot;) com1.WriteLine(data) com1.Close End Using End Sub </li>  To 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 = &quot;&quot;

Using com1 As IO.Ports.SerialPort = _ My.Computer.Ports.OpenSerialPort(&quot;COM1&quot;) Do           Dim Incoming As String = com1.ReadLine If Incoming Is Nothing Then Exit Do           Else returnStr &= Incoming & vbCrLf End If       Loop com1.Close End Using

Return returnStr End Function </li>  To read data from and write data to a serial port, add the following code to the Sub Main procedure. Dim Data As String Data = &quot;Test&quot;

Console.WriteLine(&quot;Writing the following data to COM1: &quot; & Data) SendSerialData(Data)

Console.WriteLine(&quot;Read the following data from COM1: &quot; & ReceiveSerialData)

Console.WriteLine(&quot;Press ENTER to quit&quot;) Console.ReadLine </li> To run the solution, press CTRL+F5.</li></ol>

<div class="references_section">