Serial Port Interfacing in Microsoft Access
An example how to use the StrokeReader ActiveX to control a serial port from Microsoft Access.
How to Proceed
- Download and install the ActiveX;
- Open the VBA IDE and add a reference to the StrokeReader ActiveX control;
- Paste the below code into a form module.
We intentionally do not place the ActiveX on a form. Instead, we dynamically create the object when the form is loading.
Anybody who wants to place the object on a form, be prepared to deal with Access bugs or manually connect to the port by setting Connected=True using a button or when the form is loading. Do not set the Connected=True in the ActiveX properties at the design time.
The Code Example
Dim WithEvents sr As StrokeReader
Private Sub Form_Load()
Set sr = CreateObject("STROKESCRIBE.StrokeReaderCtrl.1")
sr.Port = 3 ' Specify your serial port number here
sr.BaudRate = 9600
sr.Parity = NOPARITY
sr.DataBits = 8
sr.StopBits = ONESTOPBIT
sr.Connected = True
If sr.Error Then
Debug.Print sr.ErrorDescription
End If
End Sub
Private Sub Form_UnLoad(Cancel As Integer)
Set sr = Nothing ' Destroys the serial port object when the form is unloading
End Sub
' The serial port event handler.
' The data reception process is asynchronous. You don't need to poll the port.
Private Sub sr_CommEvent(ByVal Evt As StrokeReaderLib.Event, ByVal data As Variant)
Select Case Evt
Case EVT_DISCONNECT
Debug.Print "Disconnected"
Case EVT_CONNECT
Debug.Print "Connected"
Case EVT_DATA
buf = sr.Read(TEXT) ' Use BINARY to receive a byte array
Debug.Print buf
End Select
End Sub
Open the Immediate Window (press Ctrl+G in VBA) to see output of the Debug.Print statements.
Sending the Data
If you want to send data to to the remote device, use the following code:
Sub send()
sr.Send "ABCD" ' A text string
End Sub
To send an array of bytes, use this code:
Sub send()
Dim x(3) As Byte 'A byte array
x(1) = 1
x(2) = 2
x(3) = 3
sr.Send x
End Sub
Hardware Flow Control
If a serial device requires specific handshaking, use the following code to control the state of DTR/RTS lines:
sr.DTR = True
sr.RTS = True