Arduino on Jetson TK1 – Simple serial port reader for Ubuntu with C++

In this post, we will show how to develop a simple serial port reader for Ubuntu using C++; it is the first step if you want to enable a device (your Arduino project, for example) communicating via software with a Jetson TK1 board.

As a demo project, we will use the simple test of photo resistor functionalities from Arduino Playground.

Ubuntu, as any other Linux distribution, provides access to serial ports as device files; in order to access the Arduino serial port, you have to find the corresponding file and open it.In order to do so, access the /dev/serial/by-id folder; you will  find a “usb-Arduino_xxxx” file.

Right click and read the link target: it will look like: ../../ttyACM0;  /dev/ttyACM0 is the data stream file to open:

int fd = open( "/dev/ttyACM0", O_RDWR| O_NOCTTY );

The O_RDWR flag grants reading and writing privileges while the O_NOCTTY tells the system that the program isn’t the controlling terminal of the port.
For more information, visit the GNU web site.

By including  the <termios.h> file, you will be able to use POSIX  standards to set the properties of serial communication with ports.
By the POSIX functions tcgetattr() and tcsetattr() we will get and set  all the serial options.
Here is the complete code:

#include <stdio.h>      
#include <unistd.h>     
#include <fcntl.h>      
#include <errno.h>      
#include <termios.h>    
#include <iostream>

using namespace std;

int main()
    int  serial_port = open( "/dev/ttyACM0", O_RDWR| O_NOCTTY );
    fcntl(serial_port, F_SETFL, 0);

    /*Define the POSIX structure*/
    struct termios _serial_options;

    /*Read the attribute structure*/
    tcgetattr(serial_port, &serial_options);

    /*Set the baud rate of the port  to 9600*/
    cfsetispeed(&serial_options, B9600);
    cfsetospeed(&serial_options, B9600);
            serial_options.c_cflag |= (CLOCAL | CREAD);

    /*Define other parameters in order to  realize the 8N1 standard*/
    serial_options.c_cflag &= ~PARENB;
    serial_options.c_cflag &= ~CSTOPB;
    serial_options.c_cflag &= ~CSIZE;
    serial_options.c_cflag |= CS8;

    /*Apply the new attributes */
    tcsetattr(serial_port, TCSANOW, &serial_options);

    /*Now, we read the first 100 line from the data stream, then we close the port */

    char buf[1000];

    for(int i=0; i<100;i++) {
        read( serial_port, &buf , VEOL);
        std::cout << "Read: " << buf << endl;

    return 0;


You may download it from our Github repository.

Ps. Make sure your user has the correct grants to read the device serial file.

Leave a Reply

Your email address will not be published. Required fields are marked *