Ask Your Question

ROS Subscriber Listner String Message

asked 2017-01-28 04:13:57 -0500

newbieros gravatar image

updated 2017-01-29 04:32:17 -0500

gvdhoorn gravatar image

this is the subscriber node from ros tutorials:

void chatterCallback(const std_msgs::String::ConstPtr& msg) 
  ROS_INFO("I heard: [%s]", msg->data.c_str());

My string array consists of msg which is shown in image, Now i need to access a particular element in the msg (message consists first time and next CAN message, I want to use particularly CAN.ID whic is arrays second element) any suggestion. thanks in advance

edit retag flag offensive close merge delete


First: std_msgs/String is a very bad choice for this, as it has no semantics whatsoever. a String is not the same as a CAN frame, even though both consists of a 'string' of bytes.

gvdhoorn gravatar image gvdhoorn  ( 2017-01-28 05:50:44 -0500 )edit

Second: if possible, see if you can reuse something that already exists. It could save you a lot of effort.

Perhaps ros_canopen can do what you need.

gvdhoorn gravatar image gvdhoorn  ( 2017-01-28 05:51:21 -0500 )edit

I am using some CAN USB interface, where I am using those receive and transmit nodes which are already existed for this hardware type. So the message that they have used here is std_msgs/String.

newbieros gravatar image newbieros  ( 2017-01-28 22:01:58 -0500 )edit

1 Answer

Sort by ยป oldest newest most voted

answered 2017-01-29 04:31:14 -0500

gvdhoorn gravatar image

updated 2017-01-29 04:34:14 -0500

C++'s std::string class provides an indexing operator implementation that lets you access individual characters in the string. See std::string::operator[] for details.

In your particular case, you could do something like:

size_t my_index = ...;
char the_byte = msg->data[my_index];

Now the_byte contains the char at position my_index in msg->data (which is of type std::string (wiki/msg)).

As I wrote in my comment on your OP though: std_msgs/String is really not a good message to use for interfacing with CAN wrappers (or for storing byte buffers in, period).

edit flag offensive delete link more


Note btw that this is not something that is ROS specific at all. It's a basic C++ question.

gvdhoorn gravatar image gvdhoorn  ( 2017-01-29 04:33:56 -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



Asked: 2017-01-28 04:13:57 -0500

Seen: 367 times

Last updated: Jan 29 '17