Communicating through a serial port in C is pretty simple once it’s set up; you just read and write to it as though it was a file. The setting up, however, can be a real pain. Here’s the short and simple way to get it done.

Note that this code requires the following headers:

#include <fcntl.h>
#include <termios.h>

int fd; /* port file descriptor */
char port[20] = “/dev/ttyS0”; /* port to connect to */
speed_t baud = B9600; /* baud rate */

fd = open(port, O_RDWR); /* connect to port */

/* set the other settings (in this case, 9600 8N1) */
struct termios settings;
tcgetattr(fd, &settings);

cfsetospeed(&settings, baud); /* baud rate */
settings.c_cflag &= ~PARENB; /* no parity */
settings.c_cflag &= ~CSTOPB; /* 1 stop bit */
settings.c_cflag &= ~CSIZE;
settings.c_cflag |= CS8 | CLOCAL; /* 8 bits */
settings.c_lflag = ICANON; /* canonical mode */
settings.c_oflag &= ~OPOST; /* raw output */

tcsetattr(fd, TCSANOW, &settings); /* apply the settings */
tcflush(fd, TCOFLUSH);

/* — code to use the port here — */

close(fd); /* cleanup */

  1. Karel Paul-Hus says:

    Hi,

    I tried this code to set up a USB connection so instead of /dev/ttyS0, I have /dev/ttyUSB0 but I can’t open the port. I get this error just after the line with the open:

    Can’t find a source file at “/build/buildd/eglibc-2.17/io/../sysdeps/unix/syscall-template.S”
    Locate the file or edit the source lookup path to include its location.

    Do you have an idea of what this means ?

  2. Irunfold says:

    Thank you for this sample because I was trying with hard with 20+ settings in an attempt to open a serial port for communication… whereas this example is simple and working.

  3. Las Vegas says:

    Simple and perfect. Thank you so much!

  4. yuruk says:

    Whoever will use this code please note that it’s missing the input side of the initialization:

    //setting input speed
    cfsetispeed(&settings, baud); /* baud rate */

    //flushing unread buffer data
    tcflush(fd, TCIFLUSH);

  5. Robert says:

    This is exactly what I have been looking for. Where can one find more about ‘C’ and ‘serial ports’.