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

Subscriber callback not triggering while in a while loop

asked 2020-05-12 06:10:50 -0600

jlepers gravatar image


I would like to create a subscriber that uses the callback to get the data, but that is also able to do things with that data in the main loop (where the node is declared).

Here is a simple example of the code: (using rclcpp_info as an example)

uint16_t message;

void chatterCallback(const std_msgs::msg::UInt16::SharedPtr msg)
    message = msg->data;

int main(int argc, char * argv[])
   // creating node + subscriber

    rclcpp::init(argc, argv);
    auto node = rclcpp::Node::make_shared("listener");
    auto sub = node->create_subscription<std_msgs::msg::UInt16>
    ( "chatter", chatterCallback, rmw_qos_profile_sensor_data);

   // using the message of the callback

    while (rclcpp::ok())
      RCLCPP_INFO(rclcpp::get_logger("rclcpp"), message);

return 0;

The problem is that the callback is not triggering because I'm in a while loop. But if I remove the while loop, the main program is only running once. How could I solve this issue ?

I see 2 possible solution:

  • I need to be able to create a loop in the main function that doesn't interrupts with the callback function.

  • Or is it possible to create a node class and everytime there is a callback, this would call a method in the node class. Something simular as in this question (, but where the method is called directly from the callback function

Thanks !

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2020-05-12 08:28:09 -0600

ipa-jba gravatar image

Without checking or too much experience in ros2:

your rclcpp::spin(node) is only after the while loop. So your node is not added to an executor and callbacks won't be executed. In ROS 2 there is rclcpp::spin_some(node) which looks like the thing you are looking for. Add the spin_some statement inside of your while loop and remove the spin(node).

I would be happy if you provide feedback on this answer.

edit flag offensive delete link more

Question Tools



Asked: 2020-05-12 06:10:50 -0600

Seen: 2,754 times

Last updated: May 12 '20