scenprogs-logo

raspberry pi gpio uart serial (write, read) interfacing with c++ using unix api

software 30.01.16 scenprogs

Because there are many options reading and writing from serial port through terminal or popular libraries you may want to have more access of port hardware using unix api.

As mentioned in the title sometimes the capabilities of libraries don’t fit with the needs of your project and we have to face libraries which are lower in software layer. Just imagine a fully customized hardware serial protocol. This article should help you to get a sight into serial port programming with unix api and for example a raspberry pi.

access privileges for the raspberry pi serial port

The raspberry pi’s (GPIO) serial port is located under the interface path /dev/ttyAMA0. The default user pi normally has the needed rights to access the serialport but if you use different users you must give them access privileges for the serial port. The following terminal command changes the access privileges for the serialport.

sudo chmod a+rw /dev/ttyAMA0

logic level difference

Before you start wiring up your circuits take care of logic level differences between your devices. The rasperry pi’s works with 3.3V logic level whichs is for example not compatible with a 5V logic level of an arduino board. If you face logic level differences you have to use a logic level converter between your devices. There are many low priced modules on the market which fits to 3.3 and 5V.

init serial port

The following function open_serial() is used to open and configure the physical comport.  Setting up serial port for unix means basicly setting the right flags in the termios struct. The object (handle) to access the serial port is called filedescriptor and given back through the function open(). The function tcsetattr() is used to commit the modified termios struct which contains the configuration for the serial port. The configurations flags for the termios struct are grouped into input mode flags, output mode flags, control mode flags, local mode flags and control characters flags.

write string function

read string function

the whole code sticked together