2.1 Simple Connection between ROS and Arduino

2.1.1 Hardware Setup

Before we begin coding, let's start by wiring the Arduino to the PC. You need the following components:

  • Arduino Nano (or Uno)

  • USB cable to connect Arduino to PC

  • Jumper wires

Wiring:

  • Connect the Arduino to your PC using a USB cable.

2.1.2 ROS-Arduino Serial Communication

First, we need to install the required Python packages for serial communication:

In Ubuntu:

sudo apt update
sudo apt install python3-serial

In Windows (WSL2): Ensure that WSL has access to your USB ports. Install the pyserial package:

pip install pyserial

2.1.3 Writing ROS Node for Serial Communication

The first step is writing a simple ROS node in Python that sends a command over serial to the Arduino.

Create a ROS package if you haven’t already:

You will now have a new folder within your workspace’s src directory called ros_arduino_basic.

Here’s a simple ROS node that communicates with the Arduino:

ser_basic.py:

Make sure to modify /dev/ttyUSB0 to match the correct serial port for your Arduino.


2.1.4 Uploading Arduino Code

Now, upload a simple Arduino sketch to receive data from ROS.

Arduino Sketch:

Upload this code to your Arduino using the Arduino IDE.

If Arduino shows error:

Please Read

It might happen that when you upload a sketch - after you have selected your board and the serial port -, you get an error Error opening serial port ... If you get this error, you need to set serial port permission.

Open Terminal and type:

you will get something like:

The "0" at the end of USB might be a different number, or multiple entries might be returned. The data we need is "dialout" (is the group owner of the file).

Now we just need to add our user to the group:

where

is your Linux user name. You will need to log out and log in again for this change to take effect.

Adding user to the group.
Adding user to the group.

This is the procedure to access the serial port from the Arduino Software (IDE) if you get an error

After this procedure, you should be able to proceed normally and upload the sketch to your board or use the Serial Monitor.


2.1.5 Running the Code

  1. Install colcon

  1. Open a terminal on your PC and source ROS 2:

  2. Run the ROS node:

Now you can see commands being sent from ROS to Arduino. Check the Arduino Serial Monitor to see the received data.


Last updated