Robotics StackExchange | Archived questions

subscribing and publishing to a twist message

I am trying to subscribe to a topic depending on which I have different values to be published to a twist message. I am using the following code. However when I run this node and check the topic with rostopic echo cmd_vel , i see that the value of 2 is not being assigned to msg.linear.x which remains equal to zero. What am I doing wrong?

    #!/usr/bin/env python
    import rospy
    from std_msgs.msg import String
    #added
    from geometry_msgs.msg import Twist 


    def callback(data):

    global msg
    if data.data=="Unknown":

      pub_ = rospy.Publisher('cmd_vel', Twist)
        rospy.loginfo("Classifiers output: %s in unknown" % data.data)
        msg.linear.x = 2
        msg.linear.y = 0
        msg.linear.x = 0
        msg.angular.z = 0
        speed = 0.4 
        rospy.loginfo("checking for cmd" + str(msg.linear))
        pub_.publish(msg)

    elif data.data=="Check":
        rospy.loginfo("Classifiers output: %s in check" % data.data)
    else:      
        rospy.loginfo("Classifiers output: %s and not unknown or check" % data.data)


def listener():

     global msg
     rospy.init_node('listener', anonymous=True)
     msg = Twist()
     rospy.Subscriber("chatter", String, callback)
     rospy.spin()


if __name__ == '__main__':


     listener()

Asked by uzair on 2014-02-21 17:29:04 UTC

Comments

Format your code correctly; all lines should be indented an additional 4 spaces.

Asked by forrestv on 2014-02-22 09:16:04 UTC

sorry i didnt know about the indentation..

Asked by uzair on 2014-02-22 10:07:00 UTC

Answers

You should be making your publisher within the global scope, not within the callback. (Though that wouldn't create the problem you describe; it would result in no messages being published.)

Asked by forrestv on 2014-02-21 18:52:51 UTC

Comments

BUt the message is being published. But linear.x=0 is what i see..I dont understand why

Asked by uzair on 2014-02-22 08:30:13 UTC

You set msg.linear.x = 2, and then two lines later you reset it to 0

Asked by ahendrix on 2014-02-22 10:10:03 UTC

Hah, yep ... I'm going to blame missing that on the (previously) horrible code formatting.

Asked by forrestv on 2014-02-22 10:26:36 UTC

I dont know how i didnt see that! thank you so much guys!

Asked by uzair on 2014-02-22 17:42:13 UTC