Template for a ROS Subscriber Using rosserial on Arduino

A few weeks ago I started writing a series of tutorials that ease the work of beginners in ROS. The first tutorial was about a template for a publisher node, the second tutorial was about a template for a subscriber node in ROS, the third tutorial was a simple ROS subscriber and publisher in Python, and the fourth template is about a publisher using rosserial.

Today, I continue the series of tutorials with a template for a ROS subscriber using rosserial on the Arduino board. In addition, I’ll write a subscriber node based on the below template.

Below you will find the template for a ROS subscriber using rosserial on the Arduino board. To write your own subscriber using rosserial on Arduino, copy the template into Arduino IDE, delete the information that you don’t need and replace the text in capital letters.

ROS and Arduino

#include <ros.h>
#include <std_msgs/THE_TYPE_OF_THE_MESSAGE_YOU_SUBSCRIBER>

//create the ros node nh. The node will be used to publish to Arduino
ros::NodeHandle nh;


void messageCb(const std_msgs::MESSAGE_TYPE& msg)
{
  do_domething with msg.data;
 
}

ros::Subscriber sub("THE_TOPIC_THAT_SUBSCRIBER", &messageCb);

void setup()
{
  nh.initNode();
  nh.subscribe(sub);
}

void loop()
{
  nh.spinOnce();
  delay(10);
}

I used the above template to write a ROS node that will subscribe to a node that generates random numbers.

#include <ros.h>
#include <std_msgs/Int32.h>

ros::NodeHandle nh;

float var;

void messageCb(const std_msgs::Int32 &msg)
{
  var=msg.data;
 
  if(var > 2000)
   digitalWrite(13, HIGH);   // blink the led
      else
   digitalWrite(13, LOW);   // turn off the led
}

ros::Subscriber sub("rand_no", &messageCb);

void setup()
{
  pinMode(13, OUTPUT);
  nh.initNode();
  nh.subscribe(sub);
}

void loop()
{
  nh.spinOnce();
  delay(200);
}

How to run the node
Step 1: Open a new Terminal, type roscore and press the Enter key;
Step 2: Open a new Terminal and run the node to publish the messages;
Step 3: Open another Terminal and start the subscriber node by typing the following command:

rosrun rosserial_python serial_node.py /dev/ttyACM0

Commerce Content is independent of articles and advertising, and if you buy something through our posts, I may get a small share of the sale.

Leave a Reply

Required fields are marked *.