Wednesday, April 18, 2012

How to Use the Serial Port in Visual Basic


1. Open Microsoft Visual Studio and select 'File->New->Project' from the primary file menu. Then, choose 'Project Types->Visual Basic Projects' and select the 'Console Application' under the templates menu.
2. Right click the project icon and select the 'Add Reference' menu option. Then, choose the 'Com' menu tab and select 'Microsoft Comm Control 6.0' that is listed under 'Component Name'. Choose 'Select' followed by the 'OK' button.
3. Double-click the program module visible in the Visual Basic IDE. This will open the programming window.
4. Input the following programming code to initialize the serial port data structures that will be used to manipulate the serial port once opened:
Dim MSComm1 As MSComm
MSComm1 = New MSComm
Dim Buffer As String
MSComm1.CommPort = 1
MSComm1.Settings = '9600,N,8,1'
MSComm1.InputLen = 0
5. Open the serial port by including the following programming code after the last line of code entered in step 4:
MSComm1.PortOpen = True
MSComm1.InputMode() = InputModeConstants.comInputModeText
MSComm1.InBufferCount() = 0
MSComm1.Output = 'ATV1Q0' & Chr(13)
6. Manipulate the serial port information and then close the serial port by entering the following code at the bottom of the Visual Basic programming module:
Do
Buffer = Buffer & MSComm1.Input
Loop Until InStr(Buffer, 'OK' & vbCrLf)
MSComm1.PortOpen = False
Console.WriteLine('Close the serial port.')
EndModule
7. Select the 'CTRL+F5' keys simultaneously to build and run the project.