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

Revision history [back]

click to hide/show revision 1
initial version

ros::spin() will not return until the node has been shut down. Thus, you have no control over your program while ROS is spinning. The advantage of ros::spinOnce() is that it will check for callbacks/service calls/etc only as often as you call it. Why is this useful? Being able to control the rate at which ROS updates allows you to do certain calculations at a certain frequency.

If, for example, you have an accelerometer that samples at 100Hz. At each update of the accelerometer, it registers a callback in your program. That means that your program is processing the accelerometer data 100 times per second. Let's say you want to read that data and save it to a file five times per second (5Hz). If you're using ros::spin(), your program will only process the callback functions at 100Hz. If you use ros::spinOnce(), you can interject your own code at your desired frequency:

int main()
{
  ros::Rate loop_rate(5); // 5Hz

  while (ros::ok())
  {
    Myclass.saveDataToFile();
    loop_rate.sleep();
    ros::spinOnce();
  }
}

This allows you to execute your own code in between ROS's callback handling.