How to Read Serial Ports Using Visual Basic

Even if modems have been replaced with high speed Internet access, some computers still use them for communication. If you're programming an application that uses a modem, verifying it exists and functions is important for the user interface. Microsoft .NET includes a name space and class to communicate with serial ports.

Things You'll Need

  • Visual Studio .NET
Show More

Instructions

  1. Open a New Project

    • 1

      Create a new console application. From the Visual Studio menu, click "New" and select "Project."

    • 2

      Select "Visual Basic" on the left side of the window. On the right side are different project templates. Select "Console Application." Click the "OK" button. A new application is setup in the Visual Studio workspace.

    • 3

      Right-click the project name in the top right box in the workspace. Select "Add Reference."

    • 4

      Click the "COM" tab. Select "Microsoft Comm Control 6.0" from the listbox, and click "Select." Click "OK" to close the reference window.

    Setup the Serial Port

    • 5

      Create a new COM variable. You need to allocate memory and declare a new variable. The text below calls the COM class for use in the rest of the module. The buffer variable is used to hold the response text from the serial port.
      Dim myPort As MSComm
      myPort = New MSComm
      Dim myBuffer As String

    • 6

      Set the port to 1. Most computers come with two serial ports. The code below sets communication to port 1.
      myPort.CommPort = 1

    • 7

      Create common settings. Set the baud rate and stop bit information necessary for modem control. This sets
      myPort.Settings = "9600,N,8,1"

    • 8

      Read the whole buffer. This code makes the modem use the entire buffer of information when sent to the serial port.
      myPort.InputLen = 0

    Communicate with the Port

    • 9

      Open the serial port. The serial port needs to be opened and the input buffer cleared before the application can communicate with it. The third line of code tells the serial port to return text to the application.
      myPort.PortOpen = True
      myPort.InBufferCount() = 0
      myPort.InputMode() = InputModeConstants.comInputModeText

    • 10

      Send a command to the serial port. This command tests the response from the modem.
      myPort.Output = "ATV1Q0" & Chr(13)

    • 11

      Read the response from the serial port. This loop reads the text returned until an "OK" is reached.
      DomyBuffer = myBuffer & myPort.Input
      Loop Until InStr(myBuffer, "OK" & vbCrLf)

    • 12

      Close the port. After using the serial port, it's important to close it for other applications.
      myPort.PortOpen = False

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured