Search code examples
pythonros

How to subscribe AMCL pose and print it as the rate of ground truth pose?


I would like to print /amcl_pose same as the ground_truth/state default time-step. Hence, I have developed coding to subscribe /amcl_pose and print it in looping using while not rospy.is_shutdown() as shown in the figure below. I have developed this coding because when I used rostopic echo /amcl_pose its only print one value of the pose at one time, not based on default time-step. But, my coding have problem. When I move the robot to another place, the x,y,z value is not updated and still print the initial value of the robot's pose. How can I print the /amcl_pose value same as the ground_truth/state default time-step?

#! /usr/bin/env python

import rospy
from geometry_msgs.msg import PoseWithCovarianceStamped   

def callback(msg):
    global d
    d = msg.pose.pose.position
    while not rospy.is_shutdown(): 
        print (d)
        rospy.Rate(10)

rospy.init_node("read_pose")
sub = rospy.Subscriber('/amcl_pose', PoseWithCovarianceStamped, callback)
rospy.spin()

Solution

  • An issue you have is looping inside the callback. This will essentially block forever and result in you only seeing one value. Instead you should cache the value in the callback and simply read it in a main loop. Note that this can also be used to replace rospy.spin(). As well, that is not the correct syntax for sleeping at a certain rate. What you're doing is only creating a rate object, not using it to sleep.

    #! /usr/bin/env python
    
    import rospy
    from geometry_msgs.msg import PoseWithCovarianceStamped   
    
    def callback(msg):
        global d
        d = msg.pose.pose.position
    
    d = None
    rospy.init_node("read_pose")
    sub = rospy.Subscriber('/amcl_pose', PoseWithCovarianceStamped, callback)
    rate = rospy.Rate(10)
    while not rospy.is_shutdown():
        if d is not None:
            print(d)
        rate.sleep() #Sleep at 10Hz