Serial Port Communication
The sample code linked to this page consists of a VB module containing a
collection of routines to perform serial port I/O without using the Microsoft
Comm Control component. The module uses the Windows API to perform the
overlapped I/O operations necessary for serial communications.
The communication routines can handle up to 4 serial ports which are identified
with a Port ID. All routines (with the exception of CommRead and CommWrite)
return an error code or 0 if no error occurs. The routine CommGetError can
be used to get the complete error message.
Download Source Code
This sample was created and submitted by David M. Hitchner. If you have any
questions or comments concerning these routines, David can be reached at
The routines in this module facilitate most operations associated with serial
communication by encapsulating the API details in easy to call wrapper
functions. For example, the CommOpen routine can be used to open and
initialize a serial port.
CommOpen takes three parameters: the Port ID mentioned above, a port name
such as "COM1" and the desired communication settings (Example: "baud=9600
parity=N data=8 stop=1").
CommOpen checks to see if the specified port is open. If not, it opens it
with a call to the CreateFile API for generic read
and write access. Next the port's input and output buffers are initialized by
calling the SetupComm API followed by a call to
PurgeComm. PurgeComm insures the newly created buffers are clean.
After this, the time-out parameters for all of the port's read and write
operations are set by populating a COMMTIMEOUTS structure
and passing it to the SetCommTimeouts function.
CommOpen now sets the control settings (baud rate, parity, etc.) for the
port. To do this the current settings are: retrieved into a DCB
(Device-Control Block) structure via GetCommState,
modified as desired using a call to BuildCommDCB,
and set with the SetCommState function.
Once this is done, the CommWrite routine can be used to write to the
port. As you can see, these routines perform the bulk of the work for you. All
you need to do is call them appropriately.
See the .BAS module and .TXT file for further details.
Download this project and look at the SampleCode.txt file. This file contains
samples calls to the communication functions contained in the .BAS module.