Robotics StackExchange | Archived questions

Using global variables with a subscriber

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

Asked by PGTKing on 2022-11-07 18:53:20 UTC

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.

Asked by ravijoshi on 2022-11-07 23:01:58 UTC

Answers

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().

Asked by ljaniec on 2022-11-08 04:14:17 UTC

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.

Asked by Mike Scheutzow on 2022-11-08 15:45:17 UTC