准备工作
创建文件夹
mkdir -p catkin_ws/src
catkin_make
创建包和依赖项
cd catkin_ws/src
catkin_create_pkg xx_pkg rospy roscpp std_msgs
编写发布者
在src下建立c++文件
写代码
#include "ros/ros.h"
#include "std_msgs/String.h"
int main(int argc, char *argv[])
{
ros::init(argc,argv,"chao_node");
printf("helloworld\n");
ros::NodeHandle nh;
ros::Publisher pub= nh.advertise<std_msgs::String>("huati",10);
ros::Rate r(2);
while(ros::ok())
{
printf("开始发布\n");
std_msgs::String msg;
msg.data="oi";
pub.publish(msg);
r.sleep();
}
return 0;
}
修改CMakeLists.txt
add_executable(chao_node src/chao_node.cpp)
target_link_libraries(chao_node
${catkin_LIBRARIES}
)
编写订阅者
#include "ros/ros.h"
#include "std_msgs/String.h"
void calllback1(std_msgs::String msg)
{
ROS_INFO(msg.data.c_str());
}
void calllback2(std_msgs::String msg)
{
ROS_INFO(msg.data.c_str());
}
int main(int argc,char *argv[])
{
ros::init(argc,argv,"rx_node");
ros::NodeHandle rx;
ros::Subscriber sub= rx.subscribe("huati",2,calllback1);
ros::Subscriber sub2= rx.subscribe("huati_2",2,calllback2);
ros::Rate r(2);
while(ros::ok())
{
ros::spinOnce();
}
return 0;
}
同样修改修改CMakeLists.txt
联系
launch文件使用节点
<launch>
<node pkg= "ss_pkg" type= "chao_node" name="chao_node"/>
<node pkg= "ss_pkg" type= "tx_node" name="tx_node"/>
<node pkg= "dd_pkg" type= "rx_node" name="rx_node" output="screen"/>
</launch>
注意"/" 的使用