DelphiSerialPort is a lightweight, blocking serial port communication library for Windows using Delphi (Object Pascal). It wraps Win32 serial APIs into a clean object-oriented interface (TCommPort) and includes a demo VCL application (Project1) for interactive testing.
- Simple serial port abstraction for COM devices (RS-232/RS-485, modem, microcontroller)
- Port configuration: baud rate, data bits, stop bits, parity, RTS control
- Blocking read/write with configurable timeouts
- Byte/Buffer and text methods (
ReadBytes,ReadString,WriteBuffer,WriteString) - Error handling via
ECommErrorwith clear code and message - Utility methods:
PurgeCommPort,FlushCommPort,BytesAvailable,GetCommProp
ECommError: exception class with error types likeOPEN_ERROR,READ_ERROR,WRITE_ERROR,BAD_BAUD_RATE, etc.TCommPort: main class for serial port operations.
Create(ReadTimeout, WriteTimeout: DWORD)SetCommPort('\\.\\COMx')SetBaudRate,SetByteSize,SetParity,SetStopBitsor use DCBOpenCommPortRead/WriteoperationsCloseCommPortFree
SetCommPort(Port: string)/GetCommPortSetBaudRate(newBaud: DWORD)/GetBaudRateSetParity(newParity: BYTE)/GetParitySetByteSize(newByteSize: BYTE)/GetByteSizeSetStopBits(newStopBits: BYTE)/GetStopBitsSetRTS(Mode: TCommPort.RTSMode)SetCommDCBProperties/GetCommDCBProperties
WriteBuffer(const Buffer: TBytes; NumBytes: integer)WriteString(outString: string)(ASCII)ReadBytes(out Buffer: TBytes; MaxBytes: DWORD): DWORDReadString(MaxBytes: DWORD): string(ASCII)PutByte(value: BYTE)GetByte: BYTEBytesAvailable: DWORD
PurgeCommPort(clears receive queue)FlushCommPort(flushes OS buffers)GetConnected: BOOLGetHandle: THandleGetCommProp(out properties: COMMPROP)
Wrap operations with try/except on ECommError:
try
comm.OpenCommPort;
except
on E: ECommError do
ShowMessage('Serial port failed: ' + E.Message);
end;The demo (Project1.dpr, Unit1.pas) provides a simple VCL form with controls:
- COM port string input
- baud rate, byte size, parity, stop bits comboboxes
- read and write timeout inputs
- manual open/close buttons
- text entry for WriteString
- read button with output in TMemo
- User selects port settings
actOpencreatesTCommPort, configures and opens the connectionactWriteStringsends text to deviceButton4Clickreads text from device and appends to memoactClosecloses and frees the port
uses
CommPort;
var
comm: TCommPort;
bytes: TBytes;
n: DWORD;
begin
comm := TCommPort.Create(500, 500); // 500ms read/write timeout
try
comm.SetCommPort('\\.\COM3');
comm.SetBaudRate(115200);
comm.SetByteSize(8);
comm.SetParity(NOPARITY);
comm.SetStopBits(ONESTOPBIT);
comm.OpenCommPort;
comm.WriteString('Hello');
n := comm.ReadBytes(bytes, 128);
ShowMessage(Format('Received %d bytes', [n]));
comm.CloseCommPort;
finally
comm.Free;
end;
end;- Windows-only (uses Winapi.Windows serial APIs)
- Blocking operations may block UI thread; run on background thread for responsive GUI.
- Use full device name for COM ports >= COM10 (
\\.\\COM10).
See LICENSE.
