Wrong publishing rate using ros::Rate
Hi, I was trying to use ros::Rate to control the publishing rate. However for some reason, the publishing rate obtained is not the one I expected.
Here's my code:
ros::Publisher pub1,pub2;
ros::Rate *r1,*r2;
void callbackInt(const std_msgs::Int16ConstPtr& msg) {
pub1.publish(msg);
r1->sleep();
}
void callbackString(const std_msgs::StringConstPtr& msg) {
pub2.publish(msg);
r2->sleep();
}
int main (int argc, char** argv) {
ros::init (argc, argv, "test");
ros::NodeHandle nh;
ros::Subscriber sub = nh.subscribe ("/int", 1, callbackInt );
pub1 = nh.advertise<std_msgs::Int16> ("/pubInt", 1);
ros::Subscriber sub2 = nh.subscribe ("/string", 1, callbackString );
pub2 = nh.advertise<std_msgs::String> ("/pubString", 1);
ros::Rate rate(5);
r1 = &rate;
ros::Rate rate2(5);
r2 = &rate2;
ros::spin();
}
The code should be pretty straightforward: basically I'm subscribing to two different topics (/int
and /string
) and re-publishing on different topics (/pubInt
and /pubString
) at different 5 hz (their original rate was different).
However, if I try to check the actual rate with rostopic hz
I get 5 hz for /pubInt
but half the rate (2.5) for /pubString
. Any suggestion? Am I doing something wrong?