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

Revision history [back]

click to hide/show revision 1
initial version

Hi, I just want to add a more explicit code on how to use pub.getNumSubscribers() answered by @dornhege.

If you want to publish a message, you have to make sure the connection between subscriber and publisher is already established. This can be done by:

ros::Publisher chatter_pub = n.advertise<std_msgs::Empty>("toggle_led", 1000)
while (publisher.getNumSubscribers() < 1) {
    ros::WallDuration sleep_t(0.5);    
    sleep_t.sleep();
}
// After connection are guaranteed to be established, we can publish messages now.
std_msgs::Empty msg;
chatter_pub.publish(msg);
chatter_pub.publish(msg); // Can even publish multiple times

If using while-loop, you probably do not have to worry about this problem. Because the connection is likely to be guaranteed.