0

Rosanswers logo

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.


Originally posted by Tvlad on ROS Answers with karma: 35 on 2016-09-01

Post score: 0

1 Answers1

0

Rosanswers logo

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


Originally posted by Mark Rose with karma: 1563 on 2016-09-01

This answer was ACCEPTED on the original site

Post score: 4


Original comments

Comment by Tvlad on 2016-09-05:
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.

Comment by Mark Rose on 2016-09-06:
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.

Comment by Mark Rose on 2016-09-06:
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 ...

Comment by Mark Rose on 2016-09-06:
You should read the rospy tutorials. Start with the first one.