学习视频:https://www.bilibili.com/video/BV1zt411G7Vn?p=11&spm_id_from=pageDriver
目标:通过程序订阅小海龟的坐标
工作空间和功能包使用上一个例程工作空间和功能包:点击链接
一、用c++创建订阅者代码
1.创建代码
gedit ~/catkin_ws/src/learning_topic/src/pose_subscriber.cpp
运行指令,打开pose_subscriber.cpp文件。
/***********************************************************************
Copyright 2020 GuYueHome (www.guyuehome.com).
***********************************************************************/
/**
* 该例程将订阅/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_subscriber");
// 创建节点句柄
ros::NodeHandle n;
// 创建一个Subscriber,订阅名为/turtle1/pose的topic,注册回调函数poseCallback
ros::Subscriber pose_sub = n.subscribe("/turtle1/pose", 10, poseCallback);
// 循环等待回调函数
ros::spin();
return 0;
}
将上面代码复制到pose_subscriber.cpp文件中,保存关闭。
2.配置订阅者代码编译规则
gedit ~/catkin_ws/src/learning_topic/CMakeLists.txt
运行指令,打开CMakeList.txt文件。
add_executable(pose_subscriber src/pose_subscriber.cpp)
target_link_libraries(pose_subscriber ${catkin_LIBRARIES})
将上面两行代码加入CMakeList.txt文件中,如下图所示,保存退出。
二、用python创建订阅者代码
1.创建订阅者代码
gedit ~/catkin_ws/src/learning_topic/scripts/pose_subscriber.py
运行指令,打开pose_subscriber.py文件。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
########################################################################
#### Copyright 2020 GuYueHome (www.guyuehome.com). ###
########################################################################
# 该例程将订阅/turtle1/pose话题,消息类型turtlesim::Pose
import rospy
from turtlesim.msg import Pose
def poseCallback(msg):
rospy.loginfo("Turtle pose: x:%0.6f, y:%0.6f", msg.x, msg.y)
def pose_subscriber():
# ROS节点初始化
rospy.init_node('pose_subscriber', anonymous=True)
# 创建一个Subscriber,订阅名为/turtle1/pose的topic,注册回调函数poseCallback
rospy.Subscriber("/turtle1/pose", Pose, poseCallback)
# 循环等待回调函数
rospy.spin()
if __name__ == '__main__':
pose_subscriber()
将上面代码复制到pose_subscriber.py文件中,保存关闭。
2.设置pose_subscriber.py 文件运行权限
cd ~/catkin_ws/src/learning_topic/scripts
chmod +x pose_subscriber.py
三、编译工作空间(python不需要本步骤)
命令行输入
cd ~/catkin_ws/
catkin_make
编译之后会在工作空间/devel/lib/learning_topic目录下生成pose_subscriber可执行文件
四、运行程序
1.运行roscore
roscore
2.打开新的命令窗,运行小海龟仿真器
rosrun turtlesim turtlesim_node
3.打开新的命令窗,运行指令,通过键盘让小海龟运动
rosrun turtlesim turtle_teleop_key
4.接着打开新的命令窗,运行pose_subscriber.py脚本,获取小海龟动态坐标
rosrun learning_topic pose_subscriber.py
或(运行pose_subscriber可执行文件,获取小海龟动态坐标)
rosrun learning_topic pose_subscriber
5.运行效果图如下