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

Publish message received in callback

asked 2020-01-05 17:17:24 -0500

Tony78 gravatar image

Hello,

I am trying to do a simple node subscribing to a topic which send data of type TwoInts (a custom message), and publishing the sum of what it received.

TwoInts.msg

# TwoInts.msg
int16 a
int16 b

sum.cpp

#include "ros/ros.h"
#include <beginner_tutorials/TwoInts.h>
#include "std_msgs/Int16.h"

ros::Publisher pub;

void callback(const beginner_tutorials::TwoInts::ConstPtr& msg)
{
    ROS_INFO("I heard: [%d, %d]", msg->a, msg->b);

    int sum = msg->a + msg->b;
    // OR ?
    //std_msgs::Int16 sum = msg->a + msg->b;

    //pub.publish(sum);
    pub.publish(msg->a);
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "sum");
  ros::NodeHandle n;

  pub = n.advertise<std_msgs::Int16>("sum", 1000);
  ros::Subscriber sub = n.subscribe("two_ints", 1000, callback);

  ros::spin();

  return 0;
}

My problem is to publish the message msg in the callback. The attributes a and b are of type int16, but when I try to publish them I got some errors like this one:

error: request for member ‘__getMD5Sum’ in ‘m’, which is of non-class type ‘const short int’
     return m.__getMD5Sum().c_str();

I tried many things but I do not see how to solve that...

Thanks for your help.

Mickael

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
3

answered 2020-01-09 18:22:07 -0500

borgcons gravatar image

The solution to your problem is as follows:

#include "ros/ros.h"
#include <beginner_tutorials/TwoInts.h>
#include "std_msgs/Int16.h"

ros::Publisher pub;

void callback(const beginner_tutorials::TwoInts::ConstPtr& msg)
{
    ROS_INFO("I heard: [%d, %d]", msg->a, msg->b);

    std_msgs::Int16 sum;

    sum.data = msg->a + msg->b;

    pub.publish(sum);
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "sum");
  ros::NodeHandle n;

  pub = n.advertise<std_msgs::Int16>("sum", 1000);
  ros::Subscriber sub = n.subscribe("two_ints", 1000, callback);

  ros::spin();

  return 0;
}

I believe you are confusing Int16 message with the int16 type. The Int16 message looks like this:

int16 data

The Int16 message contains a field called data that is an int16 type.

So, msg->a and msg->b get the int16 type values from the Twoints message. Now, you want to assign the result of sum of the type int16 values back into a Int16 message to publish it. This requires you to assign it to the data field.

edit flag offensive delete link more

Question Tools

Stats

Asked: 2020-01-05 16:13:38 -0500

Seen: 1,095 times

Last updated: Jan 09 '20