June 3, 2016

Raspberry PI - Arduino communication over USB serial

The Raspberry Pi is a fine little computer board with a lot of features and very good connectivity especially on version 3 with the integrated WiFi.
However, when dealing with I/O and sensors has a lot of limitations and is lacking the reliability of Arduino board and availability of libraries to interface it with any kind of device or sensor.

That's why I have decided to develop my own approach to integrate the two famous boards to fulfill my own set of requirements:
  • Use Raspberry Pi as a master device to develop the main application and connect to the Internet.
  • Use Java on the Raspberry Pi. This may sound a strange choice but I'm planning to use it to build an OSGi application for IoT.
  • Use Arduino board as a slave device to interact with several sensors.
  • Use a simple USB cable to power the Arduino board and exchange data.


This tutorial explains how to connect Arduino board to a Raspberry PI using a simple USB cable. This will power the Arduino and provide a serial communication between the two little boards.


Arduino


First step is to load and test the Arduino sketch to allow to retrieve the current milliseconds and toggle the on-board LED as described in this article.



Raspberry PI 

First step is to free the serial interface on the RasPI disabling shell and kernel messages via UART.
Run raspi-conf utility from the command prompt:

$ sudo raspi-config

Identify the Serial option and disable it. If is in the advanced menu in recent versions of Raspbian (9, A8).



Enter the following command to reboot your Raspberry Pi board:

$ sudo reboot


Install RxTx library

On the Raspberry PI side we will use the RxTx library. Install it with the following command:

sudo apt-get install librxtx-java

You can see that the native libraries are installed into the /usr/lib/jni directory and the java client is installed in /usr/share/java.

ls -la /usr/lib/jni/librxtx*
ls -la /usr/share/java/RXTX*


Java app

Import this Java project into Eclipse and build it. It is a slightly improved version of the official RxTx sample.
Now copy the three generated class files to your Raspberry Pi device into the /home/pi directory and run the following command:

java -Djava.library.path=/usr/lib/jni -cp /usr/share/java/RXTXcomm.jar:. ArduRasPi /dev/ttyUSB0 9600

This will run the ArduRasPi program connecting to Arduino on the /dev/ttyUSB0 port and 9600 baud.

You should now be able to issue commands to Arduino and receive the correct answer.





References

Arduino Vs. Raspberry Pi: Which Is The Right DIY Platform For You?
Control an Arduino from Java
Raspberry PI reads and writes data from Arduino, in Java
Arduino and Java

No comments:

Post a Comment