How to exchange data between nodes in ROS?

3k views Asked by At

I want to send data from one node to another. For example: One node is publishing data to the topic /mobile_base/commands/velocity and other one is subscribed to /mobile_base/events/bumper. Both the subscriber & publisher are working fine.

What I want to do is to make the robot move backward once the bumpers are pressed. I do not know how to send the event of bumper pressed to the other node.

The solution I thought was of using pipes or sockets or shared memory to exchange data between two nodes.

Is this the right approach? Or does ROS has a builtin method for that?

Thanks in Advance.

1

There are 1 answers

0
alexsleat On BEST ANSWER

By subscribing to the "bumper" topic, the data is available to that node. (Assuming you're using C++, as you didn't mention - the theory is the same, but obviously the syntax will differ). Using the example publish/subscribe code on the ROS website (link).

#include "ros/ros.h"
#include "std_msgs/String.h"

//Callback for bumper data
// this callback happens 
void bumperCallback(const std_msgs::String::ConstPtr& msg)
{
  //print received data for debugging
  ROS_INFO("I heard: [%s]", msg->data.c_str());
  //If the callback data contains "hit" - change to integer, float or whatever type your message is
  if(msg->data.c_str() == "hit")
      move_backwards();          // Call function to move the robot backwards
}

int main(int argc, char **argv)
{

  ros::init(argc, argv, "listener");
  ros::NodeHandle n;
  ros::Subscriber sub = n.subscribe("bumper", 1000, bumperCallback);
  ros::spin();

  return 0;
}