I am new to ROS and trying to understand this powerful tool. I am confused between the spin
and rate.sleep
functions. Could anyone help me with the difference between these two functions and when to use each one?
ROS Rate is different from a “simple” sleep functionality, because it will dynamically choose the correct amount of time to sleep to respect the given frequency. Here the ROS Rate will sleep for the amount of time needed to complete 100ms (at 10Hz). If the code takes longer, the sleep will be shorter.
ros::spin() and ros::spinOnce() are responsible to handle communication events, e.g. arriving messages. If you are subscribing to messages, services, or actions, you must call spin to process the events. While ros::spinOnce() handles the events and returns immediately, ros::spin() blocks until ROS invokes a shutdown.
In the background, ROS monitors socket connections for any topics you've subscribed to. When a message arrives, ROS pushes your subscriber callback onto a queue. It does not call it immediately. ROS only processes your callbacks when you tell it to with ros::spinOnce() .
1 Answer. rospy. spin() will effectively go into an infinite loop until it receives a shutdown signal (e.g. ctrl-c ). During that loop it will process any events that occur, such as data received on a topic or a timer triggering, when they occur but otherwise it will sleep.
ros::spin()
and ros::spinOnce()
are responsible to handle communication events, e.g. arriving messages. If you are subscribing to messages, services, or actions, you must call spin
to process the events.
While ros::spinOnce()
handles the events and returns immediately, ros::spin()
blocks until ROS invokes a shutdown. So, ros::spinOnce()
gives you more control if needed. More on that matter here: Callbacks and Spinning.
rate.sleep()
on the other hand is merely a thread sleep with a duration defined by a frequency. Here is an example
ros::Rate rate(24.);
while(ros::ok())
{
rate.sleep();
}
This loop will be executed 24 times a second or less, depends what you do inside the loop. A ros::Rate
object keeps track of how much time since the last rate.sleep()
was executed and sleep for the correct amount of time to hit the 24 Hz mark. See ros::Rate::sleep()
API.
The equivalent way in the time domain is ros::Duration::sleep()
ros::Duration duration(1./24.);
while(ros::ok())
{
duration.sleep();
}
Which one you use is just a matter of convenience.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With