ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

Revision history [back]

I think I understand what you're trying to do, but you might need to describe your project in more detail for me to be sure.

Here is an example: Your first node publishes data once every 5 seconds, but you want your second node to run some code using the most recent data received 10 times per second. Using the publisher and subscriber example your second node only executes once every five seconds which is causing the problem. Is this an accurate interpretation of your problem?

In this case you need to use a while loop in your main function to run a piece of code 10 times per second, and a subscriber and callback function which stores the data received in some global variables. The code layout should look something like this:

int globalData1;
float globalData2;
bool globalDataReceived = false;

void myCallback(package::msgTypeConstPtr& msg)
{
  globalDataReceived = true;

  globalData1 = msg.data1;
  globalData2 = msg.data2;
}

int main()
{
  ros::init("my_node");
  ros::NodeHandle nh;

  ros::Rate loopRate(10);

  ros::Subscriber sub = nh.subscribe("/my_topic", 10, myCallback);

  while (ros::ok())
  {
    if (globalDataReceived)
    {
      // Do something with the data 10 times per second
    }

    loopRate.sleep();
  }
}