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

When exactly is a callback function executed?

asked 2020-03-16 16:25:12 -0500

smarn gravatar image

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

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2020-03-17 03:37:58 -0500

Delb gravatar image

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.

edit flag offensive delete link more

Question Tools

2 followers

Stats

Asked: 2020-03-16 16:25:12 -0500

Seen: 732 times

Last updated: Mar 17 '20