How to let an Arduino and Raspberry Pi communicate with each other

I have already described in a previous article how the Arduino works and which models exist. There are plenty of articles on the Arduino itself, but few in connection with the Raspberry Pi, but this combination offers many possibilities.

Since I want to show more about the Arduino in conjunction with the Raspberry Pi, I will begin by showing the direct communication of both.

You do not need anything more than a Raspberry Pi, a USB cable and an Arduino (e.g. Uno or Nano).

Preparation

In order for the Arduino to be able to communicate with the Raspberry Pi later, corresponding code must firstly be loaded on it. The easiest way to do it is via the PC/Mac.  I have already shown here how this works.

This is just a small example of how to use the serial component. Of course, you can also respond to the inputs by starting functions, setting or reading  I/O, etc.

Commissioning on the Raspberry Pi

On the Pi additional libraries are needed, we install them first:

sudo apt-get install minicom python-serial

You should disconnect the Arduino from the Pi if you connected it, as we need to find out the port name. To do this, do the following two times: once without and once with Arduino connected via USB.

ls /dev/tty*

You will notice that at the end of the list a new name has been added (for me that is/dev/ttyUSB0). With this name, you can address the Arduino via the serial port. Because the serial connection library was installed under Python, we can easily access it.

For this we create a new file

sudo nano serialTest.py

with the following content:

and execute:

sudo python serialTest.py

The output looks like this (Ctrl + C lets you stop it):

pi@raspberrypi ~ $ sudo python serialTest.py
The following char was received: 116
The following char was received: 101
The following char was received: 115
The following char was received: 116

The output of the read in characters takes place in ASCII format (DEC for decimal, HEX for the hexadecimal code). Of course, you can also issue the character directly or react to it.

How does this help me?

For one, the Arduino offers several features that may be useful, depending on the model. In addition, the Arduino also has many digital and analog I/O pins that can be easily controlled. It could also be used as a GPIO expander, which is much easier to control. Also, you can easily communicate with Arduino libraries/programs if you do not want to run them on the Pi.

Leave a Reply

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