1、创建功能包:
catkin_create_pkg learnin_topic roscpp rospy std_msgs geometry_msgs turtlesim
2、进入src新建cpp文件:velocity_publisher.cpp ,编写code:
/***********************************************************************
Copyright 2020 GuYueHome (www.guyuehome.com).
***********************************************************************/
/**
* 该例程将发布turtle1/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);
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、在功包src的CMakeLists.txt的文件中(大约155行)加入如下的的两行code:
add_executable(velocity_publisher src/velocity_publisher.cpp)
target_link_libraries(velocity_publisher ${catkin_LIBRARIES})
(1)add_executable的条目大概是添加可执行文件的目标,和编译的源文件;
那么:velocity_publisher就是生成的目标可执行文件,
src/velocity_publisher.cpp就是编译的源文件;
(2)target_link_libraries将上面的目标文件需要的依赖从ros中获取到
4、回到工作空间目录输入:
catkin_make
进行编译一下,下面的截图是编译第二次的结果,第一次会有更多的信息,
5、在用户目录下的.bashrc加入如下的命令:
source ~/catkin_ws/devel/setup.bash
这样就不要每次都source一下;
6、
(1):运行rosrun
(2)运海龟仿真器:rosrun turtlesim turtlesim_node
(3)运行刚编译的velocity_publisher功能:
rosrun learnin_topic velocity_publisher
可以看到小海龟以及动起来了