0
$\begingroup$

Rosanswers logo

Hi, I would like to publish a message without it being of type std_msgs::msg::String.

std_msgs::msg::UInt16 statuswoord;

auto publisher = node->create_publisher<std_msgs::msg::UInt16>("motor_info", rmw_qos_profile_default);  

auto msg =  std::make_shared<std_msgs::msg::UInt16();

msg->data = statuswoord;
publisher->publish(msg);

But I get following error:

cannot convert ‘std_msgs::msg::UInt16 {aka std_msgs::msg::UInt16_std::allocator<void >}’ to std_msgs::msg::UInt16_std::allocator<void > >::_data_type {aka short unsigned int}’ in assignment msg->data = test;

In my case I need it to be UInt16, but it might happen that I need another datatype in the future. Is there a guide somewhere on casting all the std_msgs ?

Thanks!


Originally posted by jlepers on ROS Answers with karma: 39 on 2020-04-10

Post score: 0

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

Is there a guide somewhere on casting all the std_msgs ?

I don't believe this has anything to do with casting.

There are two issues with the code you show:

auto msg =  std::make_shared<std_msgs::msg::UInt16();

This line is missing the closing > (after UInt16), and:

std_msgs::msg::UInt16 statuswoord;
msg->data = statuswoord;

this can't work.

The field data is of type uint16 in the ROS 2 msg IDL (see here), which gets converted to a std::uint16_t for C++ (refer to About ROS 2 interfaces: Message description specification - Fields - Field types), which is a short unsigned int on amd64 and many other architectures.

The statuswoord variable is of type std_msgs::msg::UInt16.

You cannot assign a std_msgs::msg::UInt16 to a variable of type std::uint16_t.

To make this work, you'll have to change the type of statuswoord to std::uint16_t.


Originally posted by gvdhoorn with karma: 86574 on 2020-04-10

This answer was ACCEPTED on the original site

Post score: 1


Original comments

Comment by gvdhoorn on 2020-04-10:
Note btw that this is not really a problem specific to ROS 2: in ROS 1 a similar system was used, and publishing a message from the std_msgs package, but treating it as a primitive type also didn't work.

Comment by gvdhoorn on 2020-04-10:
Note also btw that using the std_msgs set of messages is somewhat discouraged. A short unsigned int carries almost no semantics, which makes it not very useful for publishing as a ROS message.

You may want to create a new message type, called StatusWord and give it a single field (of type uint16) called data (or something more descriptive). Then publish a StatusWord message.

This will make sure that whoever subscribes to your StatusWord knows how to deal with those kinds of messages, and it's immediately clear to consumers that they're not receiving just some random short unsigned int, but a bitmask encoding the status (of something).

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.