How to use rospy.wait_for_message

Viewed 4300

im using rospy for a project however I dont fully understand how getting messages work. I have a drone send an specific message every second, but when I try to get the message the program gets stuck (never prints "a"). What am I doing wrong?

while(continue):
        ponto_atual = rospy.wait_for_message('/uav1/control_manager/position_cmd',PositionCommand)
        print("a")
        continuar = comparar(ponto_desejado, ponto_atual)
1 Answers

The way you should handle receiving multiple messages on a topic is via a subscription object. The purpose of wait_for_message it to grab a single message.

In rospy it's very easy to setup. For example a callback for a Bool topic looks like: rospy.Subscriber('/your_topic_name',Bool,callback_function)

Now every time a message is sent on /your_topic_name the function callback_function will be called. A more complete example would look something like this:

def callback_function(msg):
    ponto_atual = msg.data
    rospy.loginfo("I received a message!")
    #Anything else you may want to do here

def run_loop():
    rate = rospy.Rate(10.0) #Run at 10Hz
    while not rospy.is_shutdown():
        self.rate.sleep()
        #Other periodic work you may need to do

if __name__ == '__main__':
    rospy.init_node('my_node')
    rospy.Subscriber('/your_topic_name',Bool,callback_function)
    run_loop()
Related