0
$\begingroup$

Rosanswers logo

Hello, I know that in general a callback function is executed when its associated topic has published values.

What I am wondering is how do the commands spin() and spinOnce() in main affect the callback's execution, because I noticed that when the spin() command is in practice not executed like in the code below the callback is also never executed even though messages are published to the topic

  ros::Rate loop_rate(0.1);
  while(ros::ok()){
    ROS_INFO("Loop: %d\n",stop_msg.data);
    stop_pub.publish(stop_msg);
    loop_rate.sleep();
  }
  ros::spin();

on the other hand, when I changed the code in main to the following everything worked perfectly:

  ros::Rate loop_rate(0.1);
  while(ros::ok()){
    ROS_INFO("Loop: %d\n",stop_msg.data);
    stop_pub.publish(stop_msg);
    loop_rate.sleep();
    ros::spinOnce();
  }

Could somebody enlighten me? Thank you


Originally posted by smarn on ROS Answers with karma: 54 on 2020-03-16

Post score: 0

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

I would suggest you to read the wiki about Callbacks and Spinning, from the introduciton :

The end result is that without a little bit of work from the user your subscription, service and other callbacks will never be called. The most common solution is ros::spin()

In your first code ros::spin() is outside the while loop so it's never called so neither are your callbacks. In your second code you are actually spinning so the behavior you describe is totally normal.

Now you should see some related questions to understand the concept of spinning : #q257361, #q11887.


Originally posted by Delb with karma: 3907 on 2020-03-17

This answer was ACCEPTED on the original site

Post score: 1

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.