Monday, August 4, 2008

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 < SerialStream.h >
#include < iostream >
#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()
{
ardu.Open(PORT);
/*The arduino must be setup to use the same baud rate*/
ardu.SetBaudRate(SerialStreamBuf::BAUD_9600);
ardu.SetCharSize(SerialStreamBuf::CHAR_SIZE_8);
}


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;
sscanf(str,"%d",&res);
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.