ros(3)发布者publisher的编程实现

1.创建功能包
cd ~/catkin_workspace/src

catkin_create_pkg learning_topic std_msgs rospy roscpp geometry_msgs turtlesim

cd ~/catkin_workspace/src/topic_publisher/src

2.编辑代码
gedit velocity_publishes.cpp

/**
 * 该例程将发布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_publishes");
 
    // 创建节点句柄
    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.编译代码
3.1修改cmakelists.txt
添加这两句:

add_executable(velocity_publishessrc/velocity_publishes.cpp)
target_link_libraries(velocity_publishes${catkin_LIBRARIES})

 

 

 

 


3.2 编译
catkin_make

3.3设置环境变量
source devel/setup.bash

为了避免每次设置在/home目录下

ctrl+h

编辑.bashrc

source /home/<user_name>/<worksapce_name>/devel/setup.bash

4运行节点
重新打开终端

roscore

运行海龟仿真器

rosrun turtlesim turtlesim_node

运行节点

rosrun <功能包名> <节点名>

rosrun topic_publisher velocity_publishes

运行的就是该编译好的工程

 

 

 

 

 



posted @ 2021-12-02 20:40  健丽  阅读(64)  评论(0编辑  收藏  举报