步骤
发布者
步骤
发布者信息
1.导入头文件
#include"ros/ros.h"
#include"std_msgs/String.h"
2.初始化ros节点
ros::init(argc,argv,"writer");
3.创建节点句柄
ros::NodeHandle nh;
4.创建发布者对象
ros::Publisher pub = nh.advertise<std_msgs::String>("article",10);
消息
1.创建被发布的消息
std_msgs::String msg;
2.编写循环
while(ros::ok)
{
msg.data = "perfect";
pub.publish(msg);
}
3.数据内容
msg.data = "perfect";
4.发布数据
pub.publish(msg);
完整代码
#include"ros/ros.h"
#include"std_msgs/String.h"
int main(int argc, char *argv[])
{
ros::init(argc,argv,"writer");
ros::NodeHandle nh;
ros::Publisher pub = nh.advertise<std_msgs::String>("article",10);
std_msgs::String msg;
while(ros::ok)
{
msg.data = "perfect";
pub.publish(msg);
}
return 0;
}
结果
无事发生(这是正确的因为没有编写日志内容) 如有想要打印可以在终端使用以下代码:
rostopic echo "话题名称"
结果如下,data会一直打印,成功!
优化
1.设置发布频率
ros::Rate rate(10);
2.消息编号与消息拼接
std::stringstream out;
out<< num << "perfect";
num++;
3.消息类型转换
msg.data = out.str();
4.用日志打印
ROS_INFO("%s",msg.data.c_str());
5.休眠
rate.sleep();
完整代码
#include"ros/ros.h"
#include"std_msgs/String.h"
#include<sstream>
int main(int argc, char *argv[])
{
ros::init(argc,argv,"writer");
ros::NodeHandle nh;
ros::Publisher pub = nh.advertise<std_msgs::String>("article",10);
std_msgs::String msg;
ros::Rate rate(10);
int num = 0;
while(ros::ok)
{
std::stringstream out;
out<< num << "perfect";
num++;
msg.data = out.str();
pub.publish(msg);
ROS_INFO("%s",msg.data.c_str());
rate.sleep();
}
return 0;
}
运行结果
订阅者
步骤
1.创建订阅者对象
ros::Subscriber sub= nh.subscribe("article",10,doMsg);
2.创建回调函数
void doMsg(const std_msgs::String::ConstPtr& msg){
ROS_INFO("我收到:%s",msg->data.c_str());
}
3.回调函数
ros::spin();
4.设置中文可以打印
setlocale(LC_ALL,"");
完整代码
#include"ros/ros.h"
#include"std_msgs/String.h"
void doMsg(const std_msgs::String::ConstPtr& msg){
ROS_INFO("我收到:%s",msg->data.c_str());
}
int main(int argc, char *argv[])
{
setlocale(LC_ALL,"");
ros::init(argc,argv,"reader");
ros::NodeHandle nh;
ros::Subscriber sub= nh.subscribe("article",10,doMsg);
ros::spin();
return 0;
}
运行结果
优化
我们会发现当先启动接收者,再启动发布者时,我们收到的数据并不全面。这是因为:发布者还未在 roscore 注册完毕
解决方法:在发布者里加入休眠语句
ros::Duration(3.0).sleep();
成功!!
缺陷
发布者窗口无法用ctrl+c停止
这是我学习的视频教程,感谢赵虚左老师的讲课。 ?www.bilibili.com/video/BV1Ci4y1L7ZZ?p=20
如有错误,敬请指正,欢迎交流,谢谢?(・ω・)ノ
|