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

Passing Variables From Callback Function to Main Python

asked 2019-05-30 14:42:37 -0600

zachary.guy gravatar image

updated 2019-05-30 15:42:55 -0600

jayess gravatar image

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!

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2019-05-30 15:47:50 -0600

jayess gravatar image

updated 2019-05-31 09:31:59 -0600

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.

edit flag offensive delete link more

Comments

1

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

jayess gravatar image jayess  ( 2019-05-30 15:48:14 -0600 )edit

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.

zachary.guy gravatar image zachary.guy  ( 2019-05-31 08:25:45 -0600 )edit

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

PeteBlackerThe3rd gravatar image PeteBlackerThe3rd  ( 2019-05-31 09:49:42 -0600 )edit

Question Tools

Stats

Asked: 2019-05-30 14:42:37 -0600

Seen: 6,039 times

Last updated: May 31 '19