本節對應趙虛左ROS書籍的2.1.2
以10hz,發布消息和消息的訂閱
1) 在功能包的src文件夾下,新建cpp文件,并且寫入
#include "ros/ros.h"
#include "std_msgs/String.h"
int main(int argc, char *argv[])
{setlocale(LC_ALL,"");ros::init(argc,argv,"talker");ros::NodeHandle nh;ros::Publisher pub =nh.advertise<std_msgs::String>("chatter",100);std_msgs::String msg;std::string msg_front ="hello,你好!";int count =0;ros::Rate r(10);while(ros::ok()){std::stringstream ss;ss << msg_front << count;msg.data=ss.str();pub.publish(msg);ROS_INFO("發送消息為%s",msg.data.c_str());r.sleep();count++;ros::spinOnce();}return 0;
}
代碼解釋? ? ? ??
1.1)包含ros頭文件? ?
#include "ros/ros.h"
? ? ? ? 包含消息類型頭文件
#include "std_msgs/String.h"
1.2) 在主函數中
加入語句,防止中文亂碼
setlocale(LC_ALL,"");
初始化節點
ros::init(argc,argv,"talker");
"talker"為節點名
實例化句柄
ros::NodeHandle nh;
實例化發布對象
ros::Publisher pub =nh.advertise<std_msgs::String>("chatter",10);
“chatter”為話題名,10為隊列長度
組織數據
std_msgs::String msg;
std::string msg_front ="hello,你好!";
int count=0;
ros::Rate r(10);
循環發布數據
while(ros::ok())//節點不死
{std::stringstream ss;//用于拼接數據ss << msg_front << count;//拼接數據msg.data=ss.str();pub.publish(msg);//發布數據ROS_INFO("發送數據為 %s",msg.data.c_str());rate.sleep();count++;ros::spinOnce();}
2)在功能包的src文件夾下,新建cpp文件,并且寫入
#include "ros/ros.h"
#include "std_msgs/String.h"
void doMsg(const std_msgs::String::ConstPtr& msg_p)
{ROS_INFO("我接受到:%s",msg_p->data.c_str());
}
int main(int argc, char *argv[])
{setlocale(LC_ALL,"");ros::init(argc,argv,"listener");ros::NodeHandle nh;ros::Subscriber sub = nh.subscribe<std_msgs::String>("chatter",100,doMsg);ros::spin();return 0;
}
代碼解釋:
實例化訂閱對象
ros::Subscribe sub=nh.subscribe<std_msgs::String>("chatter",100,doMsg);
話題‘‘chatter’’ 必須與發布方的話題相同
100 :隊列長度
doMsg :回調函數
有回調函數必須有回調循環函數
ros::spin();//回調循環函數ros::spinOnce();//在循環體中用的回調循環函數
doMsg回調函數具體寫入
void doMsg(const std_msgs::String::ConstPtr& msg_p)
{ROS_INFO("接受到消息:%s",msg_p->data.c_str());
}
3) 配置CMakeLists文件
136行,149行
4)運行rosrun
rosrun <包名> <節點名>