message publish ros code example

Example 1: c++ ros subscriber

#include "ros/ros.h"
#include "std_msgs/String.h"

/**
 * This tutorial demonstrates simple receipt of messages over the ROS system.
 */
void chatterCallback(const std_msgs::String::ConstPtr& msg)
{
  ROS_INFO("I heard: [%s]", msg->data.c_str());
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "listener");

  ros::NodeHandle n;

  ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);

  ros::spin();

  return 0;
}

Example 2: roscpp publish int32

#include <std_msgs/Int8.h>

std_msgs::Int8 msg;
msg.data = 17;
ROS_INFO("%d", msg.data);
chatter_pub.publish(msg);

Tags:

Cpp Example