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

Callback function not changing the value of Global variable

asked 2018-08-27 14:31:55 -0500

Sufyan gravatar image

updated 2018-08-27 14:57:13 -0500

i am using ar track alvar to recieve co ordinates from my camera... The data seems to be fine but i want to use this data.For this i made a subscriber as below

start = (0,0) 

def callback(msg):
    x=msg.pose.position.x
    y=msg.pose.position.y
    rospy.loginfo(rospy.get_caller_id() + "I heard x = %f", x)
    rospy.loginfo(rospy.get_caller_id() + "I heard  y= %f", y)XPos1 =x
    YPos1 =y  
    XPos1 += 0.11
    YPos1 += 0.1
    XPos1 = XPos1 * 22.69
    YPos1 = YPos1 * 24
    XPos1 = round(XPos1) -1
    YPos1 = round(YPos1) 
    XPos1 =int(XPos1)
    YPos1= int(YPos1)    
    start = (XPos1,YPos1)
    print start


print start

where start is a global variable which i initialize in the begining as start(0,0) but when my code is executed even though this call back function is invoked as i can see the value of x and y on terminal and the value of start ( which is a global variable) is also what i expected but as soon as the program exits callback function the the last print statement prints (0,0) as the value of start (which is what i initialized start variable to in the begining of program as global variable) This is the Output

[INFO] [1535398460.244633]: /listener_11195_1535398438793I heard x = 1.294724
[INFO] [1535398460.250098]: /listener_11195_1535398438793I heard  y= -0.089722

(31, 0)
^C(0, 0)
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
4

answered 2018-08-27 14:57:23 -0500

gvdhoorn gravatar image

updated 2018-08-27 15:10:53 -0500

This is most likely a Python problem, not a ROS problem.

The start in your callback(msg) method is a different variable. The name is the same, but that variable shadows the start in the global scope. To refer to the global start, add global before it.

See Python Global, Local and Nonlocal variables (random Google search result) for some more explanation.

edit flag offensive delete link more

Comments

Yes you are right it solved the problem. Thanks a lot!!!

Sufyan gravatar image Sufyan  ( 2018-08-27 15:07:36 -0500 )edit

Question Tools

1 follower

Stats

Asked: 2018-08-27 14:31:55 -0500

Seen: 7,513 times

Last updated: Aug 27 '18