ROS(4)订阅者subscriber编程实现

cd ~/catkin_workspace/src/topic_publisher/src

创建代码pose_subscribes.cpp

/**
 * 该例程将订阅/turtle1/pose话题,消息类型turtlesim::Pose
 */
 
#include <ros/ros.h>
#include "turtlesim/Pose.h"
 
// 接收到订阅的消息后,会进入消息回调函数
void poseCallback(const turtlesim::Pose::ConstPtr& msg)
{
    // 将接收到的消息打印出来
    ROS_INFO("Turtle pose: x:%0.6f, y:%0.6f", msg->x, msg->y);
}
 
int main(int argc, char **argv)
{
    // 初始化ROS节点
    ros::init(argc, argv, "pose_subscribes");
 
    // 创建节点句柄
    ros::NodeHandle n;
 
    // 创建一个Subscriber,订阅名为/turtle1/pose的topic,注册回调函数poseCallback
    ros::Subscriber pose_sub = n.subscribe("/turtle1/pose", 10, poseCallback);
 
    // 循环等待回调函数
    ros::spin();
 
    return 0;
}

编译代码

修改cmakelists.txt

添加

add_executable(pose_subscribes src/pose_subscribes.cpp)
target_link_libraries(pose_subscribes ${catkin_LIBRARIES})

然后

运行小海龟

 

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