Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I read from or write to a serial (COM) port in my code?

Ports

How do I read from or write to a serial (COM) port in my code?

by  AdaHacker  Posted    (Edited  )
You can use the MSComm control to access COM ports. This will let you read or write data directly to a COM port, much like using HyperTerminal to directly access a port. You can also use this control to control a modem using AT commands.

The MSComm control comes with VB6. Add it to your project by going to the Project->Components menu item and adding "Microsoft Comm Control 6.0" to your project. You can then select the control in your toolbox and add it to a form.

Here is a very basic example of using the MSComm control. This will open COM1, send a string to the port, and get back any response from the attached device. Please note that if you need to send binary data instead of ANSI text, you will need to assign a Byte array to the .Output property instead of a string. Likewise, if you want to recieve binary data, you will need to set the .InputMode property and assign .Input to a Byte array.
Code:
Dim s As String
With MSComm1
   ' First we initialize a few properties.
   ' Set the COM port number.
   .CommPort = 1
   ' The communication settings.  The values are: 
   ' baud rate, parity, data bits, stop bits.
   .Settings = "9600,n,8,1"
   ' Recieve and send thresholds, described below.
   .RThreshold = 1
   .SThreshold = 1
   ' Open COM1 and begin communications.
   .PortOpen = True
   ' Send the string "some data" to the output buffer.
   .Output = "some data"
   ' Get the current contents of the input buffer.
   s = .Input
End With

In addition to the .Settings property, there are a number of other properties that relate to the communication protocol used for the port, such as .Handshaking, .RTSEnable, and .EOFEnable. The correct settings for each property will depend on the device with which you are attempting to communicate. If you are having trouble getting a device to respond, you should check the documentation for your device and for the MSComm control and make sure that all the control's properties are set correctly.

Doing anything interesting with the MSComm control will require using the control's OnComm event. This event will be fired whenever the .CommEvent property of the control changes, which is basically whenever anything interesting happens on the COM port. Which comm events you need to worry about will depend on what you are trying to do.

One of the more common events is comEvRecieve, which is triggered when the control recieves data from the attached device. This is useful when you need to capture a large stream of incoming data. Please note, however, that comEvRecieve is governed by the value of the .RThreshold property, which holds the number of characters that should be recieved before the OnComm event is fired. If .RThreshold is set to zero (the default), then the the OnComm will not be fired for incoming data. The same is true of .SThreshold and the comEvSend event which is fired when data is sent.

Here is an example of using the OnComm event in a very simple terminal emulator program. This program has three button (Dial, HangUp, and SendCmd) and two text boxes (CmdBox and OutputBox). It will use a modem on COM1 to dial some remote system, send it some commands entered by the user, and dump any data it gets back into a text box. (Note: This code has not been tested. It is for educational use only. Error checking and other details have been omitted for clarity)
Code:
Private Sub Form1_Load()
  With MSComm1
    .CommPort = 1
    .Settings = "9600,n,8,1"
    .RTSEnabled = True
    .RThreshold = 1
    .Handshaking = comNone
  End With
  OutputBox.Multiline = True
End Sub

' Dial a hard-coded phone number and wait for
' the modem to connect.

Private Sub Dial_Click()
  With MSComm1
    If .PortOpen Then
      MsgBox "Port already opened."
      Exit Sub
    End If
    .PortOpen = True
    .Output = "+++"
    .Output = "ATDT 5551234" & vbCrLf
    OutputBox.Text = "Dialing 555-1234"
    ' Wait for the carrier detect signal, which 
    ' indicates that the modem is connected.
    Do Until .CDHolding
      OutputBox.Text = OutputBox.Text & "."
      DoEvents
    Loop
  End With
End Sub

' Hang up the modem.

Private Sub HangUp_Click()
  OutputBox.Text = OutputBox.Text & "Hanging up."
  With MSComm1
    .Output = "+++"
    .Output = "ATH0"
    .PortOpen = False
  End With
End Sub

' Send the text entered in the command box to the
' remote system, then clear the box.

Private Sub SendCmd_Click()
  With MSComm1
    If .PortOpen Then 
      .Output = CmdBox.Text & vbCrLf
      CmdBox.Text = vbNullString
    Else
      MsgBox "Port is closed."
    End If
  End With
End Sub

Private Sub MSComm1_OnComm()
  Select Case MSComm1.CommEvent

    ' Capture any incoming data and write 
    ' it to the output box.
    Case comEvSend
      OutputBox.Text = OutputBox.Text & MSComm1.Input

    ' Capture changes in the carrier detect line. 
    ' This will detect if the modem has been 
    'disconnected.
    Case comEvCD
      If Not MSComm1.CDHolding Then
        HangUp_Click
        OutputBox.Text = OutputBox.Text & "Disconnected."
      End If

  End Select
End Sub
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top