Ask Your Question
0

How to create ROS subscriber which will remember the last message until the new one?

asked 2016-09-01 10:31:43 -0500

Tvlad gravatar image

Hello. I use python. I want to use the loop based on data of Publisher. For example, If I get the data == 1, I need to print "Hello" every 3 seconds, until when I will receive the new message with another data. Please help me.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
4

answered 2016-09-01 15:05:31 -0500

Mark Rose gravatar image

Subscriber callbacks run on their own thread, so I usually update a variable in the subscriber callback and then use that data in a main loop running in the startup thread. Something like this:

import rospy

class MyNode:
    def main(self):
        rospy.subscriber('sometopic', SomeMsgType, self.msgCallback)
        self.value = None
        self.rate = rospy.getParam('~rate', 10.0)
        while not rospy.is_shutdown():
            ... do something with self.value ...
            rate.sleep()

    def msgCallback(self, newValue):
        self.value = newValue

if __name__ == '__main__':
    try:
        MyNode().main()
    except rospy.ROSInterruptException:
        pass
edit flag offensive delete link more

Comments

Thank you, but I have a question. For what we use the line:

self.value = None

And, Can I use the loop like this:

while self.value == "data":

Sorry If it's the stupid questions.

Tvlad gravatar image Tvlad  ( 2016-09-05 02:32:27 -0500 )edit

You have to set a value for self.value before the while loop runs. Python will throw an exception if you try to access an attribute that doesn't exist. I just chose None so you can determine that no value has been received yet. I'm not sure if I understand your loop question.

Mark Rose gravatar image Mark Rose  ( 2016-09-06 18:05:08 -0500 )edit

The main loop must be while not rospy.is_shutdown() so that you will exit if the ROS core shuts down. You'll probably want to check for None within the loop:

if self.value is not None:
    ... do something ...
Mark Rose gravatar image Mark Rose  ( 2016-09-06 18:06:24 -0500 )edit
1

You should read the rospy tutorials. Start with the first one.

Mark Rose gravatar image Mark Rose  ( 2016-09-06 18:09:21 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2016-09-01 10:31:43 -0500

Seen: 101 times

Last updated: Sep 01 '16