Delphi Serial Port Component for Windows, Linux and macOS
One non-visual component for COM ports, USB serial adapters and RS-485 buses. Receive with an event or with a blocking read, write from any thread, and run the same code on Windows, Linux and macOS.
Included in sgcWebSockets Enterprise (Delphi and .NET) and All-Access, or as the standalone sgcIndustrial pack.
A serial port component that behaves the same everywhere
Barcode scanners, scales, GPS receivers, modems, lab instruments and RS-485 field buses, from one Pascal class.
A Delphi serial port component has to deal with three operating systems that do serial I/O in different ways: overlapped I/O and DCB settings on Windows, termios and file descriptors on Linux and macOS. TsgcSerialPort hides all of it behind one set of properties (Port, BaudRate, DataBits, Parity, StopBits, FlowControl, RtsControl) and one set of calls, so a VCL, FMX, service or console application opens COM3 on Windows and /dev/ttyUSB0 on Linux with the same code.
Data arrives in a background reader thread. Assign OnData to get every chunk as an event, or leave it empty and the bytes go to a 64 KB receive buffer that you read with Read, with a timeout for the first byte and an inter-character timeout that ends the message. Writes are serialized by the component, so any thread can send.
Component class
TsgcSerialPort, in the sgcIndustrial unit
Port names
COM3, \\.\COM12, /dev/ttyUSB0 or just ttyUSB0
Line settings
5 to 8 data bits; none, odd, even, mark or space parity; 1, 1.5 or 2 stop bits; RTS/CTS, DTR/DSR or XON/XOFF flow control
Platforms
Delphi 7 to Delphi 13 and C++Builder; Windows 32 and 64 bit, Linux 64 bit and macOS
QuickStart
Open a port, send a command, read the answer
Three ways to use the component. Every sample compiles with Delphi 7 and Delphi 13.
uses
SysUtils, sgcIndustrial; // Delphi 7 to 2006: add sgcBase_Helpers (TBytes)procedure TForm1.FormCreate(Sender: TObject);
begin
Serial := TsgcSerialPort.Create(Self);
Serial.Port := 'COM3'; // '/dev/ttyUSB0' on Linux, '/dev/cu.usbserial-10' on macOS
Serial.BaudRate := 115200;
Serial.DataBits := 8;
Serial.Parity := spNone;
Serial.StopBits := ssOne;
Serial.FlowControl := sfcNone;
Serial.OnData := SerialData; // a reader thread receives, the event is queued
Serial.OnError := SerialError; // to the main thread (NotifyEvents)
Serial.Active := True;
Serial.WriteString('AT' + #13);
end;
procedure TForm1.SerialData(Sender: TObject; const aData: TBytes);
begin
Memo1.Lines.Add(Format('%d bytes received', [Length(aData)]));
end;
procedure TForm1.SerialError(Sender: TObject; const aError: string);
begin
Memo1.Lines.Add('error: ' + aError);
end;
procedure TForm1.btnQueryClick(Sender: TObject);
var
vData: TBytes;
vCount: Integer;
begin
Serial.OnData := nil; // without OnData, bytes go to the 64 KB receive buffer
Serial.Port := 'COM5';
Serial.BaudRate := 9600;
Serial.Active := True;
Serial.Purge;
Serial.WriteString('MEAS?' + #13#10);
// wait up to 1 s for the first byte, then return after 50 ms of silence// or when 256 bytes have arrived
vCount := Serial.Read(vData, 256, 1000, 50);
if vCount = 0then
Memo1.Lines.Add('timeout')
else
Memo1.Lines.Add(Format('%d bytes', [vCount]));
Serial.Active := False;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin// COM1, COM3, ... on Windows; /dev/ttyUSB0, /dev/ttyACM0, ... on Linux
TsgcSerialPort.ListPorts(ComboBox1.Items);
Serial := TsgcSerialPort.Create(Self);
Serial.Port := 'COM4';
Serial.BaudRate := 38400;
Serial.Parity := spEven;
Serial.RtsControl := srcToggle; // RS-485 half duplex: RTS on while sending
Serial.WriteTimeout := 500;
Serial.Active := True;
Serial.SetDTR(True);
if smsCTS in Serial.ModemStatus then
Memo1.Lines.Add('CTS is on');
end;
Features
The details that make serial code reliable
Threads, timeouts, buffers and unplugged adapters, handled inside the component.
Event or blocking read
With OnData assigned, every chunk the reader thread receives is delivered as an event. Without it, Read(Data, MaxCount, Timeout, InterCharTimeout) waits for the first byte, then returns when MaxCount bytes arrived or the line stayed silent for the inter-character time: the natural way to read one framed answer.
Events on the thread you choose
NotifyEvents queues OnData, OnOpen, OnClose and OnError to the main thread by default, can synchronize them, or can raise them directly in the reader thread for the lowest latency.
Write from any thread
Write and WriteString are serialized by an internal lock. Write returns the bytes written, WriteTimeout limits how long it waits, and WriteString sends the UTF-8 bytes of a string and raises if they could not all be written.
Close from anywhere
Close is safe from any thread, even from inside an OnData handler. It wakes a blocked Read, cancels a blocked write and stops the reader thread, using overlapped I/O cancellation on Windows and a cancel flag with poll on Linux and macOS.
RS-485 direction control
RtsControl := srcToggle raises RTS while the port transmits and drops it afterwards, so an RS-485 transceiver releases the bus for the answer. Windows uses the driver's RTS toggle mode, Linux the kernel RS-485 mode of the serial driver.
Modem lines
SetDTR and SetRTS drive the output lines; ModemStatus returns the set of active inputs: smsCTS, smsDSR, smsRI and smsDCD.
Port discovery
TsgcSerialPort.ListPorts adds the port names to any TStrings in natural order (COM2 before COM10): from the registry on Windows, /dev/ttyS*, /dev/ttyUSB* and /dev/ttyACM* on Linux, and /dev/cu.* on macOS.
Buffers under control
BufferCount tells how many bytes wait in the 64 KB receive buffer and Purge empties it together with the operating system buffers. If the buffer overflows, the oldest bytes are dropped and OnError fires once.
Errors with the OS code
Every failure raises EsgcSerialError, whose ErrorCode holds the Windows error or the POSIX errno. When a USB adapter is unplugged, OnError fires once and the port waits for Close. On Linux and macOS the port is opened in exclusive mode.
Platforms
What each operating system supports
A setting the platform cannot do raises EsgcSerialError at Open instead of being ignored.
Feature
Windows
Linux
macOS
Baud rates
Any rate the driver accepts
Standard rates, 50 to 4,000,000
Standard rates, 50 to 230,400
Mark and space parity
Yes
Yes
No
RTS/CTS and XON/XOFF flow control
Yes
Yes
Yes
DTR/DSR flow control
Yes
No
No
RS-485 RTS toggle
Yes, driver toggle mode
Yes, kernel RS-485 mode (driver support needed)
No
Port list
Registry
/dev/ttyS*, ttyUSB*, ttyACM*
/dev/cu.*
The component is tested on a real COM port on Windows (32 and 64 bit) and on pseudo terminals on Linux 64 bit; the same code compiles for macOS. Android and iOS are not supported.
Modbus RTU
The transport for Modbus RTU
TsgcSerialPort is also the serial line under the Delphi Modbus RTU components. Assign an open port to the SerialPort property of TsgcModbusRTUClient to poll slaves on an RS-485 bus, or of TsgcModbusRTUServer to answer as a slave. The Modbus components take care of the 3.5 character frame gap, the CRC and the slave address; the port only needs the line settings of the bus, typically 19200 baud, 8 data bits, even parity and 1 stop bit.
FAQ
Delphi serial port questions
Create a TsgcSerialPort, set Port (for example COM3), BaudRate, DataBits, Parity and StopBits, and set Active := True or call Open. Ports above COM9 work with the plain name too; the component adds the \\.\ prefix Windows needs.
Leave OnData unassigned and call Read(Data, MaxCount, Timeout, InterCharTimeout). It waits up to Timeout milliseconds for the first byte, then returns when MaxCount bytes have arrived or no byte came for InterCharTimeout milliseconds. The result is the number of bytes read, and 0 means a timeout. Only one thread should call Read at a time.
Yes, with any adapter the operating system exposes as a serial port: a COM port on Windows, /dev/ttyUSB* or /dev/ttyACM* on Linux, /dev/cu.* on macOS. If the adapter is unplugged while the port is open, OnError fires once; call Close and open the port again when the adapter is back.
Converters with automatic direction control need no setting. For converters driven by RTS, set RtsControl := srcToggle: RTS is raised while the port transmits and dropped when the last byte has left. Windows does it in the serial driver and Linux in the kernel RS-485 mode, which the serial driver must support; otherwise Open raises a clear EsgcSerialError.
Writes can come from any thread and are serialized by the component. Close can be called from any thread, including the reader thread inside an event handler. Reads are meant for one caller at a time, which is how a request and response protocol uses a serial line anyway.
Delphi 7 to Delphi 13 and C++Builder, on Windows 32 and 64 bit, Linux 64 bit and macOS. Android and iOS are not supported.
TsgcSerialPort is included in sgcWebSockets Enterprise (Delphi and .NET) and All-Access, or in the standalone sgcIndustrial pack, together with the Modbus components.