ros的topic:创建消息类型、发布、订阅

来源:互联网 发布:微信软件源 编辑:程序博客网 时间:2024/05/18 02:21

1、创建消息

英文网页:http://wiki.ros.org/ROS/Tutorials/CreatingMsgAndSrv

msg是一个文本文档,包括前缀和数据类型,前缀:

 Header header  头,时间戳和所在坐标系  string child_frame_id  子坐标系(还没搞明白) 
每行一个数据类型,数据类型可以是:
  • int8, int16, int32, int64 (plus uint*) 
  • float32, float64
  • string 字符串
  • time, duration 时间
  • other msg files 其他封装消息
  • variable-length array[] and fixed-length array[C] 动态数组和静态数组

(1)创建消息文件

工程中,创建msg/Student.msg

写入:

[cpp] view plaincopy
  1. string name  
  2. uint8 age  
  3. uint32 score  
(2)制作

CMakelists.txt中添加

rosbuild_genmsg()
用于生成Student.h文件

查看:rosmsg show Student


2、发布消息

(1)初始化ros系统

(2)广播消息

[cpp] view plaincopy
  1.   ros::Publisher chatter_pub = n.advertise<beginner_tutorials::Student>("chatter", 1000);//发布的消息类型,topic名称,缓存的消息数  

(3)填充消息数据,指定频率发布

[cpp] view plaincopy
  1. msg.data = ss.str();//填充消息内容  
[cpp] view plaincopy
  1. chatter_pub.publish(msg);//发布消息  

[cpp] view plaincopy
  1. #include "ros/ros.h"  
  2. #include "std_msgs/String.h"  
  3. #include "beginner_tutorials/Student.h"  
  4. #include <sstream>  
  5.   
  6.   
  7. int main(int argc, char **argv)  
  8. {  
  9.   ros::init(argc, argv, "talker");  
  10.   ros::NodeHandle n;  
  11.   ros::Publisher chatter_pub = n.advertise<beginner_tutorials::Student>("chatter", 1000);  
  12.   ros::Rate loop_rate(10);  
  13.   int count = 0;  
  14.   while (ros::ok())  
  15.   {  
  16.     beginner_tutorials::Student msg;  
  17.   
  18.     std::stringstream ss;  
  19.     ss << "john" << count;  
  20.     msg.name = ss.str();  
  21.     msg.age = count%30;  
  22.     msg.score = (count*10)%100;  
  23.   
  24.     ROS_INFO("%s", msg.name.c_str());  
  25.   
  26.     chatter_pub.publish(msg);  
  27.     ros::spinOnce();  
  28.     loop_rate.sleep();  
  29.     ++count;  
  30.   }  
  31.   return 0;  
  32. }  


3 收听消息

(1)消息回调函数

[cpp] view plaincopy
  1. void chatterCallback(const beginner_tutorials::Student::ConstPtr& msg)  
(2)订阅消息
[cpp] view plaincopy
  1. ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);//订阅主题/chatter,新消息到达时,调用函数ChatterCallback  
(3)循环等待,消息到达时工作,没到达时休息
[cpp] view plaincopy
  1. ros::spin();//循环接收  
[cpp] view plaincopy
  1. <pre name="code" class="cpp">#include "ros/ros.h"  
  2. #include "std_msgs/String.h"  
  3. #include "beginner_tutorials/Student.h"  
  4.   
  5. void chatterCallback(const beginner_tutorials::Student::ConstPtr& msg)  
  6. {  
  7.   ROS_INFO("I heard: [%s] [%d] [%d]", msg->name.c_str(),msg->age,msg->score);  
  8. }  
  9.   
  10. int main(int argc, char **argv)  
  11. {  
  12.   
  13.   ros::init(argc, argv, "listener");  
  14.   
  15.   ros::NodeHandle n;  
  16.   
  17.   ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);  
  18.   
  19.   ros::spin();  
  20.   return 0;  
  21. }  
  22. // %EndTag(FULLTEXT)%</pre><br><br> 
0 0
原创粉丝点击