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

Revision history [back]

You essentially have the code, you just need to modify your rate value. Right now you have 50 which will run at 50Hz (i.e. 50 times per second), so you should set that value to 1 so that it runs only once per second. Your code would be:

 int main()
 {
     //Declaration part
     ros::Rate rate(1); // periodic at 1 cycle per second
     while(ros::ok())
     {
         // Run your function and check condition

         // Modify the message based on the condition

         // Publish the message

         rate.sleep(); // runs out whatever duration is remaining for the 1 second interval
         ros::spinOnce();
     }
 }

Using the Rate is better than Timer in this case because the Timer will run for 1 second irrespective of how much time was spent processing in the loop prior to the timer call, whereas Rate will try to maintain your loop running at the period you specify. For example, if your function call took 0.5 seconds, and you run timer for 1.0 seconds, your loop in total will take 1.5 seconds. With Rate, if your function call takes 0.5 seconds, the Rate will fill in the remaining 0.5 seconds, and your loop will take 1.0 seconds in total. This page gives a nice overview of these differences.

You essentially have the code, you just need to modify your rate value. Right now you have 50 which will run at 50Hz (i.e. 50 times per second), so you should set that value to 1 so that it runs only once per second. Your code would be:

 int main()
 {
     //Declaration part
     ros::Rate rate(1); // periodic at 1 cycle per second
     while(ros::ok())
     {
         // Run your function and check condition

         // Modify the message based on the condition

         // Publish the message

         rate.sleep(); // runs out whatever duration is remaining for the 1 second interval
         ros::spinOnce();
     }
 }

Using the Rate is better than Timer in this case because the Timer will run for 1 second irrespective of how much time was spent processing in the loop prior to the timer call, whereas Rate will try to maintain your loop running at the period you specify. For example, if your function call took 0.5 seconds, and you run timer for 1.0 seconds, your loop in total will take 1.5 seconds. With Rate, if your function call takes 0.5 seconds, the Rate will fill in the remaining 0.5 seconds, and your loop will take 1.0 seconds in total. This page gives a nice overview of these differences.your options.