cSerialPort Methods Reference
📋 Methods List
Open/Close
| Method | Return Type | Description |
|---|---|---|
OpenPort | Boolean | Open serial port |
ClosePort | - | Close serial port |
ApplyConfig | - | Re-apply configuration to opened port |
RefreshConfig | - | Read current configuration from port |
Read
| Method | Return Type | Description |
|---|---|---|
ReadData | Long | Read byte array |
ReadText | String | Read text |
ReadExisting | String | Non-blocking read of all existing data |
ReadByte | Integer | Read single byte (0~255), returns -1 on timeout |
ReadLine | String | Read one line |
Write
| Method | Return Type | Description |
|---|---|---|
WriteData | Long | Write byte array |
WriteText | Long | Write text |
WriteByte | - | Write single byte |
WriteLine | Long | Write one line (auto-append newline) |
TransmitImmediate | Boolean | Priority transmit character, bypass buffer |
Signal Lines
| Method | Description |
|---|---|
SetDTR | Set DTR signal |
SetRTS | Set RTS signal |
SetBreak | Set/clear Break signal |
SendXOff | Send XOFF |
SendXOn | Send XON |
Buffers
| Method | Description |
|---|---|
PurgeRx | Clear receive buffer |
PurgeTx | Clear transmit buffer |
PurgeAll | Clear all buffers |
Monitoring
| Method | Return Type | Description |
|---|---|---|
StartMonitoring | Boolean | Start asynchronous monitoring |
StopMonitoring | - | Stop monitoring |
WaitForEvent | Long | Blocking wait for event (use cautiously) |
GetEventMask | Long | Get current event mask |
Diagnostics
| Method | Return Type | Description |
|---|---|---|
GetStatusString | String | Get complete status string |
ReadCommErrors | Long | Get communication error codes |
ReadModemStatus | Long | Get Modem status word |
ResetCounters | - | Reset send/receive counters |
🔓 OpenPort
Description
Open serial port. Internally handles \\.\COMx prefix, supports COM10 and above ports.
Syntax
Public Function OpenPort(Optional ByVal Port As String, _
Optional ByVal Config As cSerialConfig) As BooleanParameters
| Parameter | Type | Description |
|---|---|---|
Port | String (optional) | Port name, e.g. "COM3" |
Config | cSerialConfig (optional) | Configuration object |
Return Value
Returns True on success, False on failure and sets LastError.
Usage Example
' Method 1: Set properties then open
sp.PortName = "COM3"
sp.Config.BaudRate = br115200
If sp.OpenPort() Then Debug.Print "Opened successfully"
' Method 2: Parameter method
Dim cfg As New cSerialConfig
cfg.BaudRate = br9600
sp.OpenPort "COM3", cfgOpening Process
1. CreateFile opens \\.\COMx
2. SetupComm sets buffer sizes
3. SetCommState applies DCB configuration
4. SetCommTimeouts applies timeout configuration
5. PurgeComm clears buffers🔒 ClosePort
Description
Close serial port and release handle. Stops monitoring first if active.
sp.ClosePort
Class_Terminateautomatically calls this method.
📤 WriteText
Description
Write text, converts to ANSI bytes using StrConv before sending.
Syntax
Public Function WriteText(ByVal Text As String) As LongReturn Value
Actual number of bytes written.
Dim n As Long
n = sp.WriteText("Hello")
Debug.Print "Sent " & n & " bytes"📤 WriteData
Description
Write byte array, suitable for binary protocols.
Syntax
Public Function WriteData(Buffer() As Byte) As LongDim buf(2) As Byte
buf(0) = &H41: buf(1) = &H42: buf(2) = &H43
sp.WriteData buf ' Send ABC📤 WriteLine
Description
Write one line of text, automatically appends newline (default vbCrLf).
Syntax
Public Function WriteLine(ByVal Text As String, _
Optional ByVal Terminator As String = vbCrLf) As Longsp.WriteLine "Hello" ' Send "Hello" & vbCrLf
sp.WriteLine "Data", vbLf ' Custom terminator📤 TransmitImmediate
Description
Priority transmit character, bypasses transmit buffer and sends directly.
sp.TransmitImmediate &H55 ' Immediately send 0x55📥 ReadExisting
Description
Non-blocking read of all existing data in the input buffer.
Dim s As String
s = sp.ReadExisting()
If Len(s) > 0 Then Debug.Print "Received: " & s📥 ReadData
Description
Read byte array.
Syntax
Public Function ReadData(Buffer() As Byte, _
Optional ByVal BytesToRead As Long = -1) As LongParameters
| Parameter | Type | Description |
|---|---|---|
Buffer | Byte() | Output buffer, auto ReDim |
BytesToRead | Long (optional) | Number of bytes to read, -1 means read all |
Return Value
Actual number of bytes read.
Dim buf() As Byte
Dim n As Long
n = sp.ReadData(buf) ' Read all
n = sp.ReadData(buf, 10) ' Read up to 10 bytes📥 ReadLine
Description
Read one line, default ends with vbCrLf. May block until a complete line is received or timeout.
Syntax
Public Function ReadLine(Optional ByVal Terminator As String = vbCrLf) As Stringsp.Config.SetReadTimeout 5000 ' Set timeout
Dim line As String
line = sp.ReadLine() ' Read one line📡 StartMonitoring
Description
Start asynchronous monitoring, uses Win32 Timer to periodically poll the buffer. Triggers DataReceived event when new data is detected.
Syntax
Public Function StartMonitoring(Optional ByVal IntervalMs As Long = 50) As Booleansp.StartMonitoring 50 ' 50ms polling
sp.StartMonitoring ' Default 50ms📡 StopMonitoring
Stop asynchronous monitoring.
sp.StopMonitoring⚠️ WaitForEvent
Description
Blocking wait for communication event.
Syntax
Public Function WaitForEvent(ByVal EventMask As Long) As LongParameters
| Parameter | Type | Description |
|---|---|---|
EventMask | Long | Event combination, e.g. EV_RXCHAR Or EV_CTS |
Return Value
Actually occurred event mask, 0 on failure.
⚠️ Warning: This method blocks the calling thread! Using it on the UI thread will freeze the interface. Recommended only for background threads or console applications. Use
StartMonitoringfor regular scenarios.
🔧 SetDTR / SetRTS
Description
Manually set DTR/RTS signal lines. Note: If hardware flow control (fcRtsCts/fcDtrDsr) is configured, manual settings may be overridden by flow control.
sp.SetDTR True
sp.SetRTS True
sp.SetDTR False
sp.SetRTS False🔧 SetBreak
Description
Set or clear Break signal. Break signal holds the data line at zero state.
sp.SetBreak True ' Start sending Break
' Delay...
sp.SetBreak False ' Stop Break🧹 PurgeRx / PurgeTx / PurgeAll
Description
Clear buffers.
| Method | Description |
|---|---|
PurgeRx | Clear receive buffer |
PurgeTx | Clear transmit buffer |
PurgeAll | Clear all buffers, terminate all pending I/O |
sp.PurgeAll ' Clear all📊 GetStatusString
Description
Get complete current serial port status string for debugging.
Debug.Print sp.GetStatusString()Output example:
Port: COM3
Open: True
BaudRate: 115200
DataBits: 8
InBuffer: 0
CTS: True
Received: 128
Sent: 64
Monitoring: True🔄 ApplyConfig / RefreshConfig
| Method | Description |
|---|---|
ApplyConfig | Re-apply current Config to the opened port |
RefreshConfig | Read current DCB/timeout from port and update Config |
sp.OpenPort
sp.Config.BaudRate = br9600
sp.ApplyConfig ' Apply new configuration
sp.RefreshConfig ' Read actual configuration from port
Debug.Print sp.Config.BaudRate📊 EnumSerialPorts
Description
Enumerate available serial port numbers on the system (defined in modSerialPortAPI module).
Syntax
Public Function EnumSerialPorts() As CollectionDim ports As Collection
Set ports = EnumSerialPorts()
Dim p As Variant
For Each p In ports
Debug.Print p
NextLast Updated: 2026-07-05