Understanding ROS node APIs in Arduino

Following is a basic structure 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(); 
} 

Creating 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, and 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, similar to the other ROS client libraries. 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 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", &str_msg); 
 
void callback ( const std_msgs::String& msg){ 
  str_msg.data = msg.data; 
 
  chatter.publish( &str_msg ); 
 
} 

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

Following code shows how to define a publisher object in Arduino:

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

This next code shows how we publish the string message:

  chatter.publish( &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. 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(); 
  • Convert 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
3.143.17.27