Understanding ROS node APIs in Arduino

The following is a basic structure of the ROS Arduino node. We can see the function of each line of code:

#include <ros.h> 
 
ros::NodeHandle nh; 
 
void setup() { 
  nh.initNode(); 
} 
 
void loop() { 
  nh.spinOnce(); 
} 

The creation of NodeHandle in Arduino is done using the following line of code:

ros::NodeHandle nh; 

Note that Nodehandle should be declared before the setup() function, which will give a global scope to the NodeHandle instance called nh. The initialization of this node is done inside the setup() function:

  nh.initNode(); 

The Arduino setup() function will execute only once when the device starts. Note that we can only create one node from a serial device.

Inside the loop() function, we have to use the following line of code to execute the ROS callback once:

  nh.spinOnce(); 

We can create the Subscriber and Publisher objects in Arduino, like the other ROS client libraries. The following are the procedures for defining the subscriber and the publisher.

Here is how we define a subscriber object in Arduino:

ros::Subscriber<std_msgs::String> sub("talker", callback);

Here we define a subscriber which is subscribing a String message, where the callback is the callback function executing when a String message arrives on the talker topic. Given next is an example callback for handling the string data:

std_msgs::String str_msg; 
 
ros::Publisher chatter("chatter", &amp;str_msg); 
 
void callback ( const std_msgs::String&amp; msg){ 
  str_msg.data = msg.data; 
 
  chatter.publish( &amp;str_msg ); 
 
} 

Note that the callback(), Subscriber, and Publisher definitions will be above the setup() function for getting the global scope. Here we are receiving String data, using const std_msgs::String&amp; msg.

The following code shows how to define a publisher object in Arduino:

ros::Publisher chatter("chatter", &amp;str_msg); 

This next code shows how we publish the string message:

  chatter.publish( &amp;str_msg ); 

After defining the publisher and the subscriber, we have to initiate this inside the setup() function, using the following lines of code:

  nh.advertise(chatter); 
  nh.subscribe(sub); 

There are ROS APIs for logging from Arduino. The following are the different logging APIs supported:

nh.logdebug("Debug Statement"); 
nh.loginfo("Program info"); 
nh.logwarn("Warnings.); 
nh.logerror("Errors.."); 
nh.logfatal("Fatalities!");

We can retrieve the current ROS time in Arduino using ROS built-in functions, such as time and duration.

  • Current ROS time:
ros::Time begin = nh.now(); 
  • Converting ROS time in seconds:
double secs = nh.now().toSec(); 
  • Creating a duration in seconds:
ros::Duration ten_seconds(10, 0); 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.108.105