Serial Port Programming

Accessing the serial port is very similar across Linux and Windows. This is useful especially when interfacing with devices which make use of the FT232R USB to serial interface microchip.

Linux

FILE *dev = fopen("/dev/ttyUSB0", "rb");

struct termios options;
tcgetattr(fileno(dev), &options);
cfsetispeed(&options, B57600);
cfsetospeed(&options, B57600);
tcsetattr(fileno(dev), TCSANOW, &options);

char buf[4096];
size_t bytesread = fread(&buf, sizeof(char), 4096, dev);

fclose(dev);

Windows

HANDLE dev = CreateFile("COM1", GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);

DCB options;
GetCommState(dev, &options);
options.BaudRate = CBR_57600;
SetCommState(dev, &options);

char buf[4096];
DWORD bytesread;
ReadFile(dev, buf, 4096, &bytesread, NULL);

CloseHandle(dev);

FT232R in Windows