Interfacing Arduino with C++ and libSerial.


I know that there is a section at the Arduino Playground on interfacing the Arduino with C. However, I found it is much easier, almost trivial, to use libSerial with C++.

(libSerial works on POSIX systems. I guess Windows users could use it through Cygwin but I’m not sure)
(Update: No, they can’t)

First, you import your libraries and define the port you will be using:

#include &lt SerialStream.h &gt
#include &lt iostream &gt
#define PORT "/dev/ttyUSB0" //This is system-specific

SerialStream ardu;

using namespace std;
using namespace LibSerial;

The above code is assuming that the arduino is bound to /dev/ttyUSB0. Make sure to point the stream to the real device on you computer ;)

A new serial stream “ardu” is created.

Now let’s define a simple function to setup the Arduino for communication.

void open(){
    /*The arduino must be setup to use the same baud rate*/ 

At least in my case, this simple function is enough to have a working serial communication with the microcontroller.

Now I’ll write another simple function that sends one byte through the serial port to the arduino and then reads a string, which gets interpreted as an integer..

int get(char out){    
    int res;
    char str[SOME_BIG_SIZE];
    ardu << out;
    ardu >> str;
    return res;

See? It’s easy! :)
If for some reason you must use standard POSIX libraries, here is a great article on POSIX serial programming.

If you have any doubts, post a comment.


Rotating cubes.


A couple of days ago I got 3 LIS3LV02DQ accelerometers from Sparkfun electronics.
Today I finished a working demo showing a cube that rotates as you rotate the device.
This accelerometer has some good documentation to learn how to use it. There is also a post in some blog with a specific example for the arduino.
That example didn’t work for me, but when I wasn’t sure about something, it did help to take a peek at it. Reading the datasheet carefully is extremely important.
The arduino has built-in SPI support, which helps a lot since the accelerometer uses SPI (or I^2C) to communicate. However, it is bound to 4 specific pins in the board, and if I’m going to use the 3 accelerometers at the same time without any additional hardware, I am going to have to write a software implementation, since I would be using 12 pins.
The interface to the arduino was written in C++. It uses libSerial, which makes communicating with the arduino almost as trivial as when using Python.