包含头文件;
#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>
初始化ROS节点;
ros::init(argc,argv,"节点名称");
创建节点句柄;
ros::NodeHandle nh;
创建发布者对象;
ros::Publisher pub = nh.advertise<std_msgs::String>("话题名",话题长度)
编写发布逻辑并发布数据;
std_msgs::String msg;
//发布频率
ros::Rate rate(1);
//设置编号
int count = 0;
ros::Duration(3.0).sleep();
while(ros::ok()){
count++;
std::stringstream ss;
ss<<"hello --->"<<count;
// msg.data = "hello";
msg.data = ss.str();
pub.publish(msg);
//添加日志
ROS_INFO("发布的数据是:%s",msg.data.c_str());
rate.sleep();
}
注意:
(1)当因为中文原因出现乱码问题时,在main函数的首行位置加入:
setlocale(LC_ALL,"");