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

Trying to access information from another function

asked 2021-01-07 18:05:03 -0500

PGTKing gravatar image

updated 2021-01-13 22:48:50 -0500

jayess gravatar image

Here is my code

def callback(data):

    #rospy.loginfo(data.position[1])

    print(data.position[0])

    x = data.position[0]

    return x



def listener():

    rospy.init_node('listener')

    rospy.Subscriber('/rrbot/joint_states', JointState, callback) 
    rospy.spin()


def talker():

    pub = rospy.Publisher('/rrbot/joint1_position_controller/command', Float64, queue_size=10)
    rospy.init_node('talker', anonymous=True)

    rate = rospy.Rate(1) # 10hz
    while not rospy.is_shutdown():
        #hello_str = "hello world %s" % rospy.get_time()
        force = random.choice([-1,1])
        #force = 0
        rospy.loginfo(force)
        pub.publish(force)
        rate.sleep()
        return force

def trainer():

    force = talker()

    x = callback(data)

    print(force)
    print(x)


if __name__ == '__main__':
    try:
        trainer()
    except rospy.ROSInterruptException:
        pass

this is my error when i try to run the code

NameError: name 'data' is not defined
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-01-07 20:17:11 -0500

tryan gravatar image

To access information from another function, you have to store it in a higher-level scope. One way is with the keyword global:

z = 0  # global variable defined outside of function

def add_1(x):
    global z
    z = x + 1

print(z)  # output: 0
add_1(5)
print(z)  # output: 6

Another--often better--option is to create a class and define member variables:

class MyClass(object):
    def __init__(self):
        self.z = 0

    def add_1(self, x):
        self.z = x + 1

my_object = MyClass()
print(my_object.z)  # output: 0
my_object.add_1(5)
print(my_object.z)  # output: 6

I'm not entirely sure what you're trying to do, but if you elaborate, I'd be happy to help you further.

edit flag offensive delete link more

Comments

Just letting you know, I'm still actively trying to figure out the problem. Would greatly appreciate your help, if I hit a roadblock. I am going to try your class global variable method.

PGTKing gravatar image PGTKing  ( 2021-01-08 12:01:29 -0500 )edit

update my questionlink

PGTKing gravatar image PGTKing  ( 2021-01-13 16:44:54 -0500 )edit

Question Tools

1 follower

Stats

Asked: 2021-01-07 18:05:03 -0500

Seen: 116 times

Last updated: Jan 13 '21