Passing data between two ros call back functions

Hi,
May I ask that how to make the data from one subscriber call back function available to another subscriber call back function. I tried to add Global variable for the call back function, but it do not seems to work. E.g

rospy.Subscriber("/camera/color/image_raw", Image, showImg, queue_size=1, buff_size=2**24)  # 2 power of 24
rospy.Subscriber("/camera/aligned_depth_to_color/image_raw", Image, showDepth, queue_size=1, buff_size=2**24)

def showDepth(data2):
    global WidthPixel, HeightPixel, depth, Width, Height

def showImg(data):
    global xgOri, ygOri, xg, yg, wg, hg,count, countMax, xgOld, ygOld,DistanceMovX,DistanceMovY,prediction,xgN,ygN,velocityXN,velocityYN

I still getting the error message that “NameError: global name ‘HeightPixel’ is not defined”
May I know is there a way to solve this.
Thank you for reading this post.

You must return the value, use keyword ‘return’ at end of function along with the variables you want to return.
This link might be useful:using_return_in_functions
Also you must call the function again in the new function.

Hi @zhangmingcheng28,

Perhaps you are not using the keyword global correctly (not sure because I can’t see the complete code).

If you want any variable to be accessible to both functions, just define it outside both functions. It could be like this (just an example - do not copy :slight_smile: ):

# the variables below will be available in both functions
widthPixel = 0.0
depth = 0.0

def showDepth(data2):
    # because we need to modify `depth` we use the word global to reference it
    global depth
    depth = data2.depth
    
    # However because we are just reading `widthPixel` we don't need to "global" it
    if widthPixel > 0.0:
       whatever = depth/widthPixel

def showImg(data):
   # because we need to modify `widthPixel` we use the word global to reference it
   global widthPixel
   widthPixel = data.width
   
    # However because we are just reading `depth` we don't need to "global" it
   whatever = widthPixel * depth

The whatever variable defined in each function are local to the defining functions, but widthPixel and depth are available to both.

Thank you for the advice.

1 Like