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

Access all the fields in ROS msg

asked 2017-03-22 07:07:11 -0600

jonagf gravatar image

updated 2017-03-22 09:14:48 -0600

Thomas D gravatar image

This is probably a very simple and stupid question, but I searched everywhere, and maybe because it's so simple I can't find an answer.

I created a msg like this (and maybe Im gonna add a string later as well)

int64 intensity 
int64 location
int64 duration

And now I'm trying to give values to each of this variables and publish them in a topic. I did the follow:

// (dont know how I'll do if I had the string, but thats not the problem **yet**)
ros::Publisher chatter_pub = n.advertise<std_msgs::Int64>("chatter", 1000);
std_msgs::Int64 msg;

Now the question comes here. In the ros publisher tutorials, we use msg.data, and as I searched online I found that data was the name of our variable. However, I did not understand that. How can I give values to every field of my message? I thought on doing something like this, but I know its not correct...

msg.data.intensity = 15;
msg.data.location = 100;
msg.data.duration = 37;

//ROS_INFO("intensity %d, local %d, dura %d ", msg.data.intensity,msg.data, msg.data);
chatter_pub.publish(msg);

Thank you!!

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2017-03-22 09:21:23 -0600

Thomas D gravatar image

updated 2017-03-22 09:23:52 -0600

If you created a custom message then you need to create a Publisher that uses that custom message type. Right now your publisher is using a std_msgs/Int64 type which only has a single field named data.

Let's say your custom message is in a package called my_custom_msgs and that the file is named Custom.msg. Then you would need to declare your publisher like

ros::NodeHandle n;
ros:Publisher pub = n.advertise<my_custom_msgs::Custom>("chatter", 1000);

Now you can declare a message using the custom data type, populate each of the fields in your message, and publish.

my_custom_msgs::Custom msg;
msg.intensity = 15;
msg.location = 100;
msg.duration = 37;
pub.publish(msg);

Later, if you change your message to include a string so that it becomes

int64 intensity 
int64 location
int64 duration
string note

Then you will create the publisher the same way, but populating the fields and publishing will be

my_custom_msgs::Custom msg;
msg.intensity = 15;
msg.location = 100;
msg.duration = 37;
msg.note = "Hello";
pub.publish(msg);
edit flag offensive delete link more

Comments

Thank you very much! It was very useful! The package part was missing in my head, now it makes sense!

jonagf gravatar image jonagf  ( 2017-03-22 12:20:52 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2017-03-22 07:06:11 -0600

Seen: 3,169 times

Last updated: Mar 22 '17