Cannot set ROS2 publisher rate correctly
Hi all,
I want my publisher to publish at an high rate, for example 500 or 1000Hz. I've tried using different strategies, first:
rclcpp::Rate loop_rate(1000);
while (rclcpp::ok()) {
node_ros->publish_state();
rclcpp::spin_some(node_ros);
loop_rate.sleep();
}
But with ros2 topic hz /name
, I get an average rate of 125Hz.
So I tried to use a WallTimer
, as suggested in the
tutorial:
timer_ = this->create_wall_timer(8.5us, std::bind(&RosNode::publish_state, this));
Here I found a magic number: 8.5us that gives me an average rate of 360Hz (more or less). But there are a few things that I don't understand:
- if 8.5 microseconds is the period, then the frequency should be 1/8.5us, that is way bigger then 360Hz.
- if I set 9us, I get an average rate of 3200Hz.
I also tried to build the same code of the tutorial, changing the WallTimer
period to 1ms, in order to get a rate of 1000Hz, but instead I get an average of 160Hz.
I read that ros2 topic hz /name
can return a wrong rate, but this seems too much.
Did someone else have this problem? What am I doing wrong?
EDIT: I've done more testing. Trying to calculate my frequency using 2 timestamps taken with this->now()
, I noticed that till 100/120Hz both ros2 topic hz
and my calculations find the correct rate. Otherwise, for higher rate, I get wrong results with both!
Is this a ROS2 problem?
I think you can get a lot of knowledge from this discussion on almost the same topic: https://discourse.ros.org/t/ros2-spee... (if you haven't found it yourself before, of course (: )