Use values of a callback in another callback

asked 2020-04-09 06:30:23 -0500

cheesee61 gravatar image

Hello guys,

I need to write a rospy node, which subscribes to two topics and publishes to one topic. I want to work in callback1 with the gathered values of callback2, but I am wondering how this gonna work. The idea is like follows:

subscriber(......, callback_laserscan)
subscriber(......, callback_objectDetection)

    get angles
    get ranges

    get bounding boxes
    work with values of callback_laserscan
    publish the result to topic

How can I use the values from the laserscan callback function in my other callback function, should I implement a class where I have methods for my subscriber and publisher and save the values of callback_laserscan in a member variable? I've read that rospy is multithreaded, does that mean both functions/methods run simultaneously when a message arrives?

My setup is Ubuntu 16.04 LTS with ROS kinetic.

I appreciate every hint and help


edit retag flag offensive close merge delete


Hi @cheesee61,

Technically the callback is called every time a new message is extracted from the queue. If you want to use the value of a callback in another callback I think about two possible solutions.

  1. Use a global variable in your code.
  2. Generate a class with a member variable that stores your data.

However, in both ways I think it is very important that you take into account data races, thus, depending on what you want to do with that data you may want to include a mutex in order to avoid race conditions.

Weasfas gravatar image Weasfas  ( 2020-04-09 06:46:00 -0500 )edit

In almost all cases when both messages have std_msgs/Header fields, it would be recommended to use message_filters instead of writing something yourself with member variables, etc.

gvdhoorn gravatar image gvdhoorn  ( 2020-04-09 06:56:00 -0500 )edit

Wow, I did not know about the existence of it. That would be more suitable.

Weasfas gravatar image Weasfas  ( 2020-04-09 07:14:00 -0500 )edit

Thx to both of you guys, especially @gvdhoorn helped me a lot over the last while, thanks!

cheesee61 gravatar image cheesee61  ( 2020-04-11 18:18:02 -0500 )edit