四、publisher的编程实现
1、在工作区创建功能包
目的:创建一个使小乌龟画圆的publisher
打开工作区
cd ~/catkin_ws/src
创建工作包,不要使用大写字母命名,会编译不成功。。。
catkin_create_pkg learning_topic roscpp rospy std_msgs geometry_msgs turtlesim
2、创建publisher代码
实现publisher一般有以下步骤:
- 初始化ROS节点
- 向ROS Master注册节点信息,包括发布的话题名和话题中的消息类型
- 创建消息数据
- 按照一定频率循环发布数据
首先,在learning_topic/src目录下创建publisher代码
cd learning_topic/src
sudo gedit velocity_publisher.cpp
/**
* 该publisher将发布turtler1/cmd_vel话题,消息类型geometry_msgs::Twist
**/
#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
int main(int argc, char **argv)
{
// ROS节点初始化
ros::init(argc, argv, "velocity_publisher");
// 创建节点句柄
ros::NodeHandle n;
// 创建一个Publisher,发布名为/turtle1/cmd_vel的topic,消息类型为geometry_msgs::Twist,队列长度10
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类型的消息
geometry_msgs::Twist vel_msg;
// 小乌龟的
vel_msg.linear.x = 0.5;
vel_msg.angular.z = 0.2;
// 发布消息
turtle_vel_pub.publish(vel_msg);
count +=1;
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;
}
3、配置publisher代码编译规则
打开CMakeLists.txt
cd ~/catkin_ws/src/learning_topic
sudo gedit CMakeLists.txt
添加下列代码
## 设置需要编译的代码和生成的可执行文件
# velocity_punlisher.cpp是需要编译的代码,velocity_publisher是生成的可执行文件
add_executable(velocity_publisher src/velocity_publisher.cpp)
## 设置链接库
target_link_libraries(velocity_publisher ${
catkin_LIBRARIES})
4、编译并运行publisher
cd ~/catkin_ws
catkin_make
成功编译
Base path: /home/doublehuhu/catkin_ws
Source space: /home/doublehuhu/catkin_ws/