ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

How to use variable's value (subscriber function) in another function

asked 2014-06-30 07:21:38 -0600

jashanvir gravatar image

updated 2014-07-01 09:27:06 -0600

Hello all !

I want to pass the variable which is set to its value when called the callback function. and then want to use the value of the variable in another function.

def where1(msg):
    global x1
    x1 =

def where2(gsm):
    global y1
    y1 =
def ground():
    global x1
    global y1
    rospy.Subscriber("/box_positiona", Float64, where1)
    rospy.Subscriber("/box_positionb", Float64, where2)

    print x1
    print y1
    rospy.spin() # this will block untill you hit Ctrl+C

if __name__ == '__main__':
    except rospy.ROSInterruptException:
            rospy.loginfo("Ground  motion node is shut down.")

But i got the following error print x1 NameError: global name 'x1' is not defined

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted

answered 2014-06-30 08:00:42 -0600

dornhege gravatar image

You are printing values, i.e. x1, y1 before they have been assigned. The subscribers won't do anything until spin is called and messages are received.

edit flag offensive delete link more


But when i check by rostopic echo /box_positiona then it prints the data ?

jashanvir gravatar image jashanvir  ( 2014-06-30 08:45:19 -0600 )edit

how to get the values from the callback function and use them ? Can you give me the reference or a simple demo code which i can use. ! @dornhege

jashanvir gravatar image jashanvir  ( 2014-07-01 06:02:11 -0600 )edit

Try putting your spin() above the print statements.

McMurdo gravatar image McMurdo  ( 2014-07-01 09:56:27 -0600 )edit

@McMurdo no, it doesnt help... it prints the value when i terminate the program using ctrl+c

jashanvir gravatar image jashanvir  ( 2014-07-01 10:03:16 -0600 )edit

@McMurdo no it shows the same error, but this time when i terminate the program.

jashanvir gravatar image jashanvir  ( 2014-07-01 10:07:26 -0600 )edit

Check your own comment. The spin will retrieve the messages and BLOCK. You should handle message data in the callbacks.

dornhege gravatar image dornhege  ( 2014-07-02 06:09:10 -0600 )edit

Yeah ! I know.. But I solved the problem by putting all these in one class.

jashanvir gravatar image jashanvir  ( 2014-07-03 05:55:29 -0600 )edit

@jashanvir Hi, can you explain me how do you solved that? I have the same error, other thing, how do you do for use Float64? I am new, and a few noob, in ROS.

DannyMB gravatar image DannyMB  ( 2016-10-13 18:00:18 -0600 )edit

Question Tools

1 follower


Asked: 2014-06-30 07:21:38 -0600

Seen: 3,584 times

Last updated: Jul 01 '14