2

My question is how to pass a value from one subscriber's callback function to another.

does this make sense ?

import rospy
from sensor_msgs.msg import LaserScan, Int32
from xxx2.msg import xxyy2

global x
x = None      

def callback2(data):
    x=data[0]

def callback(data):
    if x > data.ranges[0]:
        print("nice")


rospy.Subscriber("/scan", LaserScan, callback)
rospy.Subscriber("topic", xxyy2, callback2)    
rospy.spin()

angelos.p
  • 500
  • 1
  • 5
  • 12
  • I don't think there should be an issue with this approach but you should know that you can not determine the order in which the callbacks arrive. So callback2 might get called before callback. What are you actually trying to accomplish? – Malefitz Nov 20 '19 at 11:45
  • I'm trying to compute x in one callback an then use it in another. Yes I know my callbacks are actually runing in different frequencies – Bartek Czwartek Nov 20 '19 at 13:58

2 Answers2

1

You can "pass" variable x to both callbacks as you can pass it to any other function, by making x global the way you did or by making x and the callback functions members of a class which allows you to just access them.

Callbacks are by default called sequentially so you don't need to worry about race conditions in this case.

Depending on your use case you can synchronize the callbacks with message filters if needed.

Malefitz
  • 417
  • 3
  • 7
1

I would change the code a bit, I think the way you have wrote it, the global variable is not properly setup.

The different is that instead of using the instruction global at the variable definition, you have to use it inside the callbacks.

import rospy
from sensor_msgs.msg import LaserScan, Int32
from xxx2.msg import xxyy2

x = None      

def callback2(data):
    global x
    x = data[0]

def callback(data):
    global x
    if x > data.ranges[0]:
        print("nice")


rospy.Subscriber("/scan", LaserScan, callback)
rospy.Subscriber("topic", xxyy2, callback2)    
rospy.spin()

Regards

Marco Arruda
  • 699
  • 6
  • 17