ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

How to make a loop that runs every time ros node receives a message?

asked 2014-05-10 13:40:55 -0500

mysteriousmonkey29 gravatar image

Hello, I'm trying to write a node that subscribes to a topic, then, in the callback function for the subscriber, saves each message received in a global variable (one that is overwritten each time a new message is received), and that manually republishes the messages on a different topic name every time the a message is received (like a node for manually remapping a topic). I realize that this node isn't useful in itself, but it is part of a larger program and I have to get it working before I can get the larger program working.

Does anyone know how to make a loop or event or some qualifier that I can put code inside that will run every time I receive a message on a specific topic in ROS? For now I just measured the average hz of the topic I'm subscribing to, and then set the loop rate of the publishing loop equal to that average, but I would like something more exact.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2014-05-10 16:57:25 -0500

AbuIbra gravatar image

updated 2014-05-10 17:02:22 -0500

I am not sure I exactly understood what you wanna do. But here is a suggestion:

First when you announce your publisher, specify 0 to avoid missing a msg (infinite queue: WATCH OUT! This can be dangerous..). Like this!

ros::Publisher msg_pub = nh.advertise("new_topic_name", 0);

Then just do this inside your callbacks:


Note that you do not need to create a node to change a topic name. This is easily done by just adding this line in the right place on your launch file:

<remap from="old_topic_name" to="new_topic_name"/>

edit flag offensive delete link more


Thank you, but as I said, this is a proof of concept for a larger program. That's why I'm doing it in a node instead of as a simple remap command. In the larger command, I'm trying to subscribe to multiple topics of the same type (coming from different robots), combine each message, and then republish the combined message to another topic for use by another node. This is the reason I'm doing the remapping manually here, and its also the reason I don't want to put the publishing inside the callback functions (good idea though). Because if the publishing is in the callbacks, then in the final program I can't combine the different messages into one before publishing them.

mysteriousmonkey29 gravatar image mysteriousmonkey29  ( 2014-05-11 09:48:07 -0500 )edit

Question Tools

1 follower


Asked: 2014-05-10 13:40:55 -0500

Seen: 729 times

Last updated: May 10 '14