一、一个工程结构
CATKIN_WS 目录为工作区
src 下面包含不同的包 package
二、节点定义
发布节点
#include"ros/ros.h" #include "std_msgs/String.h" int main(int argc,char **argv) { // initialize and name node ros::init(argc, argv, "publisher"); // 节点名称 //create nodeHandle ros::NodeHandle nh; //ros node handle句柄 // create publisher //<消息类型> ros::Publisher simplepub = nh.advertise<std_msgs::String>("string_topic",100);// 主题名称 // publish frequency ros::Rate rate(10); // message for publish std_msgs::String pubinfo; pubinfo.data="Hello, Im publisher"; while(ros::ok()) { simplepub.publish(pubinfo); rate.sleep(); } return 0; }
接受节点
#include "ros/ros.h" #include "std_msgs/String.h" using namespace std; void subCallback(const std_msgs::String &submsg) { string subinfo; subinfo = submsg.data; ROS_INFO("the message subscribed is: %s",subinfo.c_str()); } int main(int argc,char**argv) { //initial and name node ros::init(argc, argv, "subscriber"); //create nodehandle ros::NodeHandle nh; // ros node handle 句柄 // create subscriber // 订阅主题,传入回调函数 ros::Subscriber sub = nh.subscribe("string_topic",1000,&subCallback); // 程序运行到这里后不再往下运行 ros::spin(); return 0; }
二、编译和运行
编译
运行可以参考:
https://www.cnblogs.com/feihu-h/p/11839316.html