一、目标功能
ROS Master内有两个节点,一个是Subscriber(turtlesim),一个是Publisher,发布者通过程序实现发布Message,Message的内容包括线速度、角度,通过Topic管道,传递给Subscriber,从而控制小海龟的运动。
二、创建功能包
首先先创建一个工作空间,具体参考上一节【ROS学习笔记】(二)工作空间与功能包的创建
然后创建一个功能包
1 2
| cd ~/catkin_ws/src catkin_create_pkg learning_topic roscpp rospy std_msgs geometry_msgs turtlesim
|
三、创建发布者代码
进入功能包的src文件夹下,创建一个cpp文件(也可以在图形界面直接创建)
1 2 3
| cd ~/catkin_ws/src/learning_topic/src touch velocity_publisher.cpp sudo gedit velocity_publisher.cpp
|
输入以下代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
#include <ros/ros.h> #include <geometry_msgs/Twist.h>
int main(int argc, char **argv) { ros::init(argc, argv, "velocity_publisher");
ros::NodeHandle n;
ros::Publisher turtle_vel_pub = n.advertise<geometry_msgs::Twist>("/turtle1/cmd_vel", 10);
ros::Rate loop_rate(10);
int count = 0; while (ros::ok()) { geometry_msgs::Twist vel_msg; vel_msg.linear.x = 0.5; vel_msg.angular.z = 0.2;
turtle_vel_pub.publish(vel_msg); ROS_INFO("Publsh turtle velocity command[%0.2f m/s, %0.2f rad/s]", vel_msg.linear.x, vel_msg.angular.z);
loop_rate.sleep(); }
return 0; }
|
四、配置发布者代码编译规则
-
设置需要编译的代码和生成的可执行文件
-
设置链接库
在Learning_topic/CMakeList.txt
文件的Build下方(Install上方),添加代码如下
1 2
| add_executable(velocity_publisher src/velocity_publisher.cpp) target_link_libraries(velocity_publisher ${catkin_LIBRARIES})
|
五、编译并运行发布者Publisher
1. 编译
1 2 3
| cd ~/catkin_ws catkin_make source devel/setup.bash
|
可以在~/.bashrc
文件最后添加source语句,这样就不用每次再在终端输入source命令创建环境变量(路径中替换成自己的用户名)
1
| source /home/【Username】/catkin_ws/devel/setup.bash
|
2. 运行
1 2 3
| roscore rosrun turtlesim turtlesim_node rosrun learning_topic velocity_publisher
|
参考教程:古月ROS入门21讲
GitHub:https://github.com/guyuehome/ros_21_tutorials
Bilibili:https://www.bilibili.com/video/BV1zt411G7Vn
【ROS学习笔记】(三)发布者Publisher的实现