话不多说,操作起来!
1.首先建立ROS工程,catkin_make之后,进入src文件夹。
(这些操作想必大家都很熟练了)如果之前完全没接触过linux和ROS的话,可以顺带看一些基本操作命令,跟着下面的步骤做下来,我们都能成功!
2.在src目录下使用 catkin_create_pkg 创建一个 package 包并添加 roscpp 和 std_msgs 依赖项。
catkin_create_pkg communication_ab roscpp std_msgs
cd communication_ab/src
touch publisher_a.cpp
touch subscriber_b.cpp
publisher_a.cpp与subscriber_b.cpp 的内容如下:
#include "ros/ros.h"
#include "std_msgs/Int32.h"
int main(int argc, char **argv)
{
ros::init(argc, argv, "publisher_a");
ros::NodeHandle n;
ros::Publisher pub = n.advertise<std_msgs::Int32>("num", 1000);
ros::Rate loop_rate(10);
int count = 0;
while (ros::ok())
{
std_msgs::Int32 msg;
msg.data = count;
ROS_INFO("node_a : %d", msg.data);
pub.publish(msg);
ros::spinOnce();
loop_rate.sleep();
++count;
}
return 0;
}
#include "ros/ros.h"
#include "std_msgs/Int32.h"
void chatterCallback(const std_msgs::Int32::ConstPtr& msg)
{
ROS_INFO("node_b : %d\n", msg->data);
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "subscriber_b");
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("num", 1000, chatterCallback);
ros::spin();
return 0;
}
4.在ros_ws/src下用 catkin_create_pkg 创建 launch 包,不添加任何依赖项,再进入 ~/ros_ws/src/launch 目录,创建 run.launch 文件
cd ..
cd ..
catkin_create_pkg launch
cd launch
touch run.launch
launch 文件内容为:
<launch>
<node pkg="communication_ab" name = "node_a" type = "publisher" output="screen" />
<node pkg="communication_ab" name = "node_b" type = "subscriber" output="screen" />
</launch>
add_executable(publisher src/publisher_a.cpp)
target_link_libraries(publisher ${catkin_LIBRARIES})
add_executable(subscriber src/subscriber_b.cpp)
target_link_libraries(subscriber ${catkin_LIBRARIES})
6.cd到ros_ws下,catkin_make整个工程。
编译成功。
7.刷新工作空间,启动run.launch文件,实现节点收发。
roslaunch launch run.launch