Robotics StackExchange | Archived questions

Passing Variables From Callback Function to Main Python

Hey,

Just want to pass a some subscribed data from my callback function to my main function so I can use it to command a controller.

import rospy
from geometry_msgs.msg import PoseStamped

def callback(msg):
    x = msg.pose.position.x
    y = msg.pose.position.y
    z = msg.pose.position.z
def main():
    rospy.init_node('pose_monitor')
    rospy.Subscriber("/aruco_single/pose", PoseStamped, callback)
    print (x)
    rospy.spin()
if __name__== '__main__':
   main()

This is the error I get:

Traceback (most recent call last):
  File "/home/zachary/catkin_ws/src/panda_arm_test/src/suscriber.py", line 17, in <module>
    main()
  File "/home/zachary/catkin_ws/src/panda_arm_test/src/suscriber.py", line 14, in main
    print (x)

Would appreciate the help!

Cheers!

Asked by zachary.guy on 2019-05-30 14:42:37 UTC

Comments

Answers

At the very minimum, you should make x a global variable. For example, at the top of your program

x = None

to bring it into the global scope and in your function

def callback(msg):
    global x
    x = msg.pose.position.x

Now, using globals is ok for small, toy programs but you will quickly run into problems with anything more significant. Therefore, should look into how classes work in Python or into event-driven programming.


Edit:

Part of the issue that you're having is that rospy.spin() just blocks until the node is shutdown and the other part is you're only printing once. If you want to print more than once, either put the print inside your callback or switch to a loop in your main.

Asked by jayess on 2019-05-30 15:47:50 UTC

Comments

Note that isn't a ROS problem, but a Python one.

Asked by jayess on 2019-05-30 15:48:14 UTC

Thank you for the reply and I'm aware this is a python problem my apologies.

I did the recommended changes and the result was just printing out None. the variable x is still not being passed through to the main function.

Asked by zachary.guy on 2019-05-31 08:25:45 UTC

You need to add the global x at the start of your call back function too.

Asked by PeteBlackerThe3rd on 2019-05-31 09:49:42 UTC