ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange |
1 | initial version |
The problem might be how you're thinking about callbacks. You don't have to explicitly ask for a callback to be activated. The line
ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);
sets things up such that chatterCallback will be called (behind the scenes, in a different thread), whenever there's data on the topic "chatter". Once you pass this line, things works as if by magic.
The call to
ros::spin();
gives control to the underlying ROS machinery, and never returns. This is why, in your first example, you see the print statement fire once. Once the execution gets to the spin call, it never returns from it.
As Armin suggested, all you need in your code is
ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);
ros::spin();
and everything should work as expected. Armin's example with spinOnce() is for cases when you want to do something of your own interleaved with ROS (not including the callback code). If not, spin() is the call you want.