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

Using global variables with a subscriber

asked 2022-11-07 17:53:20 -0600

PGTKing gravatar image

updated 2022-11-07 22:02:27 -0600

ravijoshi gravatar image

Below is my code:

if __name__ == "__main__":
    rospy.init_node("robot_control_node", anonymous=True)
    rospy.Subscriber("/rx150/joint_states", JointState, get_arm_pose)

def get_arm_pose(data):
    global waistp, shoulderp, elbowp, waistv, shoulderv, elbowv
    waistp = math.degrees(data.position[5]) + 180
    shoulderp = abs(math.degrees(data.position[4]) - 90)
    elbowp = abs(math.degrees(data.position[0]) - 90)
    waistv = data.velocity[5]
    shoulderv = data.velocity[4]
    elbowv = data.velocity[0]

def simulate(episode, is_training):
    global waistp, shoulderp, elbowp, waistv, shoulderv, elbowv
    reward = 0
    max_step = 20
    is_done = False
    episode_reward = 0
    x_target = math.cos(math.radians(episode * 6)) * 200
    y_target = math.sin(math.radians(episode * 6)) * 200
    z_target = 250
    waist_force = 0
    shoulder_force = 0
    elbow_force = 0
    for step in range(max_step):
        next_obs[0] = waistp

It shows the following error:

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

Comments

You have not provided us with a working code. For example, I can not see where waistp and other variables are defined. Given this minimal information, the error message completely makes sense.

ravijoshi gravatar image ravijoshi  ( 2022-11-07 22:01:58 -0600 )edit

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-11-08 03:14:17 -0600

ljaniec gravatar image

Try to add this in the global scope:

waistp = None
shoulderp  = None
elbowp  = None
waistv  = None
shoulderv  = None
elbowv  = None

so you have these variables and can update them every get_arm_pose callback. Instead of using global variables I would move the code inside a class, e.g. class Arm().

edit flag offensive delete link more

Comments

The problem is with your order of execution: you are trying to read waistp before you assign to it. @ljaniec's solution is one way to avoid this problem.

Mike Scheutzow gravatar image Mike Scheutzow  ( 2022-11-08 14:45:17 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2022-11-07 17:53:20 -0600

Seen: 91 times

Last updated: Nov 08 '22