Archive for: July 2013

(I) Programming serial port communications

This entry is part 1 of 2 in the series Serial communications

250px-Serial_portConnections and operating system symbolic names

A serial port is a communication physical interface through which information  transfers in or out one bit at a time (in contrast to a parallel port) being, more or less compliant, with the RS-232 standard.

But serial port communications aren’t only useful for wired DE-9 connectors. it also allows us to use it with USB (ftdi), Bluetooth (serial profile) and Zigbee using virtual serial ports.


Types-usbSerial and virtual serial ports appear as  COMx in Windows operating systems (COM1, COM2, …) andin UNIX/Linux as ttySx or ttyUSBx or even ttyACMx (ttyS0, ttyS1, ttyUSB0, ttyUSB1, ttyACM0, ttyACM1,…).

For programming purposes we usually want to communicate computers with others computers, microcontrollers or other devices like GPS, LED or LCD displays.


Serial port programming in C/C++, Windows and Linux

Using the serial port is a lot  easier, but sometimes tricky. The basic commands are to open a connection, read and write over this connection and, finally, tom close it, better if using the C++ RAII idiom.

winWindows commands:
Here you can find a complete C++ for Windows example.

With these next two definitions (among others needed):

wchar_t* device

serialPortHandle = CreateFile(device, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, NULL, NULL);
if (serialPortHandle!=INVALID_HANDLE_VALUE)
ReadFile(serialPortHandle, buffer, len, &read_nbr, NULL);

if (serialPortHandle!=INVALID_HANDLE_VALUE)
WriteFile(serialPortHandle, buffer, len, &result, NULL);

linuxUnix/Linux commands:
Here you can find a complete C++ for Linux example.

With these two definitions:

int fileDescriptor;
char *device;
  • Opening a connection, open
struct termios terminalAttributes;

fileDescriptor = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_FSYNC );

// clear terminalAttributes data
memset(&terminalAttributes, 0, sizeof(struct termios));

terminalAttributes.c_cflag = B57600 | CS8 | CLOCAL | CREAD; 
terminalAttributes.c_iflag = IGNPAR |  ONLCR;
terminalAttributes.c_oflag = OPOST;
terminalAttributes.c_cc[VTIME] = 0;
terminalAttributes.c_cc[VMIN] = 1;

tcsetattr(fileDescriptor, TCSANOW, &terminalAttributes);
int n=read(fileDescriptor, buffer, len);

int n=write(fileDescriptor, buffer, len);
  • Closing the connection, close

More information:

%d bloggers like this: