Skip to content

cSerialPort Methods Reference

📋 Methods List

Open/Close

MethodReturn TypeDescription
OpenPortBooleanOpen serial port
ClosePort-Close serial port
ApplyConfig-Re-apply configuration to opened port
RefreshConfig-Read current configuration from port

Read

MethodReturn TypeDescription
ReadDataLongRead byte array
ReadTextStringRead text
ReadExistingStringNon-blocking read of all existing data
ReadByteIntegerRead single byte (0~255), returns -1 on timeout
ReadLineStringRead one line

Write

MethodReturn TypeDescription
WriteDataLongWrite byte array
WriteTextLongWrite text
WriteByte-Write single byte
WriteLineLongWrite one line (auto-append newline)
TransmitImmediateBooleanPriority transmit character, bypass buffer

Signal Lines

MethodDescription
SetDTRSet DTR signal
SetRTSSet RTS signal
SetBreakSet/clear Break signal
SendXOffSend XOFF
SendXOnSend XON

Buffers

MethodDescription
PurgeRxClear receive buffer
PurgeTxClear transmit buffer
PurgeAllClear all buffers

Monitoring

MethodReturn TypeDescription
StartMonitoringBooleanStart asynchronous monitoring
StopMonitoring-Stop monitoring
WaitForEventLongBlocking wait for event (use cautiously)
GetEventMaskLongGet current event mask

Diagnostics

MethodReturn TypeDescription
GetStatusStringStringGet complete status string
ReadCommErrorsLongGet communication error codes
ReadModemStatusLongGet Modem status word
ResetCounters-Reset send/receive counters

🔓 OpenPort

Description

Open serial port. Internally handles \\.\COMx prefix, supports COM10 and above ports.

Syntax

vb
Public Function OpenPort(Optional ByVal Port As String, _
                         Optional ByVal Config As cSerialConfig) As Boolean

Parameters

ParameterTypeDescription
PortString (optional)Port name, e.g. "COM3"
ConfigcSerialConfig (optional)Configuration object

Return Value

Returns True on success, False on failure and sets LastError.

Usage Example

vb
' 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", cfg

Opening 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.

vb
sp.ClosePort

Class_Terminate automatically calls this method.


📤 WriteText

Description

Write text, converts to ANSI bytes using StrConv before sending.

Syntax

vb
Public Function WriteText(ByVal Text As String) As Long

Return Value

Actual number of bytes written.

vb
Dim n As Long
n = sp.WriteText("Hello")
Debug.Print "Sent " & n & " bytes"

📤 WriteData

Description

Write byte array, suitable for binary protocols.

Syntax

vb
Public Function WriteData(Buffer() As Byte) As Long
vb
Dim 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

vb
Public Function WriteLine(ByVal Text As String, _
                          Optional ByVal Terminator As String = vbCrLf) As Long
vb
sp.WriteLine "Hello"           ' Send "Hello" & vbCrLf
sp.WriteLine "Data", vbLf      ' Custom terminator

📤 TransmitImmediate

Description

Priority transmit character, bypasses transmit buffer and sends directly.

vb
sp.TransmitImmediate &H55   ' Immediately send 0x55

📥 ReadExisting

Description

Non-blocking read of all existing data in the input buffer.

vb
Dim s As String
s = sp.ReadExisting()
If Len(s) > 0 Then Debug.Print "Received: " & s

📥 ReadData

Description

Read byte array.

Syntax

vb
Public Function ReadData(Buffer() As Byte, _
                         Optional ByVal BytesToRead As Long = -1) As Long

Parameters

ParameterTypeDescription
BufferByte()Output buffer, auto ReDim
BytesToReadLong (optional)Number of bytes to read, -1 means read all

Return Value

Actual number of bytes read.

vb
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

vb
Public Function ReadLine(Optional ByVal Terminator As String = vbCrLf) As String
vb
sp.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

vb
Public Function StartMonitoring(Optional ByVal IntervalMs As Long = 50) As Boolean
vb
sp.StartMonitoring 50    ' 50ms polling
sp.StartMonitoring       ' Default 50ms

📡 StopMonitoring

Stop asynchronous monitoring.

vb
sp.StopMonitoring

⚠️ WaitForEvent

Description

Blocking wait for communication event.

Syntax

vb
Public Function WaitForEvent(ByVal EventMask As Long) As Long

Parameters

ParameterTypeDescription
EventMaskLongEvent 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 StartMonitoring for 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.

vb
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.

vb
sp.SetBreak True        ' Start sending Break
' Delay...
sp.SetBreak False       ' Stop Break

🧹 PurgeRx / PurgeTx / PurgeAll

Description

Clear buffers.

MethodDescription
PurgeRxClear receive buffer
PurgeTxClear transmit buffer
PurgeAllClear all buffers, terminate all pending I/O
vb
sp.PurgeAll     ' Clear all

📊 GetStatusString

Description

Get complete current serial port status string for debugging.

vb
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

MethodDescription
ApplyConfigRe-apply current Config to the opened port
RefreshConfigRead current DCB/timeout from port and update Config
vb
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

vb
Public Function EnumSerialPorts() As Collection
vb
Dim ports As Collection
Set ports = EnumSerialPorts()
Dim p As Variant
For Each p In ports
    Debug.Print p
Next

Last Updated: 2026-07-05

VB6 and LOGO copyright of Microsoft Corporation