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

Publishing multiple variables using a single publisher

asked 2016-09-28 13:01:57 -0500

skr_robo gravatar image

updated 2016-09-28 13:11:52 -0500

I have written a publisher to publish a float32 value to a topic depth_m. Now, I need to publish two more variables and they are of type int, not float. I would like all three of these variables to be published to the same topic. I am referring to the official tutorial). Do I just replace Float32 in the following lines with Int32 and add it to the existing publisher?

ros::Publisher depth_pub = pub_.advertise<std_msgs::Float32>("depth_m", 1000);
std_msgs::Float32 msg;

I believe I will have to edit msg to a different variable name msg1, msg2. According to me the whole thing will have the following lines:

ros::Publisher depth_pub = pub_.advertise<std_msgs::Float32>("depth_m", 1000);
ros::Publisher depth_pub2 = pub_.advertise<std_msgs::Int32>("depth_m", 1000);

std_msgs::Float32 msg;
std_msgs::Int32 msg1;
std_msgs::Int32 msg2;;;;


Is this the right strategy? If do this, will the whole thing act as a single message or multiple messages? Can I avoid two advertise lines by using just std_msgs instead of std_msgs::Float32?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2016-09-28 13:08:37 -0500

gvdhoorn gravatar image

You cannot publish multiple different types of messages to the same topic. The ROS middleware does not support that. Each type will need its own topic.

You have two options:

  1. if there is no correlation between your Float32 and your Int32 values (ie: they just happen to be published by the same program, but do not share any relationship), you could do what you are doing now: just create two separate publishers and use those.
  2. if it makes sense for all three values to be published as a single message, you could create a new custom message containing three fields (two of type int32, one of type float32). Then create a publisher that publishes your custom message type instead of the Int32 or Float32 you have now. See the Creating a ROS msg and srv tutorial for how to do that.

Note that I'd only recommend using option 2 if this makes sense for your data flows. Don't put things together just because it allows you to "avoid two advertise lines".

edit flag offensive delete link more


Actually the three values are related and it would be helpful for them to stay together. I will try creating custom message type and will update soon. Thank You.

skr_robo gravatar image skr_robo  ( 2016-09-28 13:16:50 -0500 )edit

It worked. Thank You.

skr_robo gravatar image skr_robo  ( 2016-09-28 18:38:22 -0500 )edit

Question Tools

1 follower


Asked: 2016-09-28 13:01:57 -0500

Seen: 7,776 times

Last updated: Sep 28 '16