May 9, 2024

Arduino-ROS Interface with Python – Send Messages From Python/ROS to Arduino and Receive Messages Back – Tutorial


In this tutorial, we will learn how to

  1. Write a ROS Python node that will publish (send) messages to Arduino. The Python publisher node will publish messages to a topic, and Arduino will subscribe to the same topic.
  2. Write Arduino code that will interpret these messages, change them, and publish them to another topic.
  3. Write a ROS Python node that will subscribe itself to a topic, and that will receive the messages back from Arduino.

The significance of this tutorial is in fact that this type of communication is often used in a control system for a mobile robot. Namely, a low level Arduino microcontroller will control actuators/motors and receive information from sensors. The Arduino microcontroller should receive commands from a higher-level controller. For example, a higher level controller controlling a mobile robot determined that the center of the mass of the robot should move to the new location. Its sends x and y coordinates of the desired position of the center of the mass to Arduino. Arduino then needs to control the motors such that the robot actually moves to the desired location. At the same time, Arduino needs to send back to the higher-level controller current robot position and orientation while the robot is moving.

The YouTube tutorial accompanying this webpage is given below.

The communication diagram that we will implement in this tutorial is given below.

STEP 1: Create a Workspace and Create a Package

First, we create the workspace. Open a terminal and type;

mkdir -p ~/ros_arduino_ws/src
cd ~/ros_arduino_ws
catkin_make

Then, we need to source the current workspace. We do that by typing:

source ~/ros_arduino_ws/devel/setup.bash

Then, we need to create a package. We do that by typing

cd ~/ros_arduino_ws/src
catkin_create_pkg arduino_test_comm std_msgs rospy roscpp

We use the ROS command “catkin_create_pkg” to create the package. The name of the package is “arduino_test_comm” and this package depends on the following ROS packages: “std_msgs”, “rospy”, “roscpp”. The package “std_msgs” is the package for standard communication messages, such as String, Int, Float, as well as data structures determining the position and velocity of the robot. The packages “rospy” and “roscpp” enable us to write nodes in Python and C++, respectively.