Reputation: 23
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()
Upvotes: 2
Views: 4681
Reputation: 709
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
Upvotes: 1
Reputation: 417
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.
Upvotes: 1