Ah I see what you mean, in that case you have three options depending on which message you want to parse quicker:
Store twist, wait for sonar:
Create a class variable to store the Twist message, then in the vel_cmd callback only do a stored_twist = msg;
or something like that.
Afterwards in the sonar callback node you can then always check the stored_twist
and process it along with the sonar data. The stored_twist
will get updated every time and the sonar message will work with the latest version received.
Since roscpp processes callbacks single threaded (by default) you have no danger of the vel_cmd
changing the stored_twist
while you’re working on it in the range_sub
. Still, I’d make a deep copy at the very first line before using it just to be safe in case that ever changes.
Store sonar, wait for twist:
This is probably the better option, since sonar messages should arrive at a lower frequency, but the principle is the same.
You make a variable to store the Range message, something like stored_range = msg;
and then access it in the vel_cmd
callback when processing.
Process at a fixed frequency
The third option is to store both the range and twist message in each callback and do nothing else, so that you have the latest messages stored.
Then you can process both of them at the same time in int main
, where it’s doing the spins:
ros::Rate r(20);
while (ros::ok())
{
ros::spinOnce(); //callbacks update the stored vars here in theory
geometry_msgs::Twist latest_twist;
latest_twist = yourclass.stored_twist;
sensor_msgs::Range latest_range;
latest_range = yourclass.stored_range;
//TODO process data using both
r.sleep();
}
This won’t react to a brand new message until the rate timer comes around of course, but it’ll be giving updates at a constant frequency which is sometimes better. It’s a more “game loop” style approach.
Of course this one will run even if no new data is received from both callbacks, so if that’s something you need I’d add a boolean “has_changed” that gets set to true by the callbacks and to false by the loop, and the loop only processes if the value is true.
Anyhow my cpp is a bit rusty, I mainly write python these days so take that as more of a pseudocode.