目录
- 如何实现一个订阅者
- C++
- 编写程序
- 配置CMakeLists.txt
- 编译并运行发布者
- python
- 创建并编写脚本
- 运行
平台:华硕 Thinker Edge R 瑞芯微 RK3399Pro
固件版本:Tinker_Edge_R-Debian-Stretch-V1.0.4-20200615
记录自【古月居】古月·ROS入门21讲 | 一学就会的ROS机器人入门教程 —— 古月居GYH P11 11.订阅者Subscriber的编程实现
如何实现一个订阅者
- 初始化ROS节点;
- 订阅需要的话题;
- 循环等待话题消息,接收到消息后进入回调函数;
- 在回调函数中完成消息处理。
C++
编写程序
nano ~/catkin_workspace/src/learning_topic/src/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,注册回调函数poseCallbackros::Subscriber pose_sub = n.subscribe("/turtle1/pose", 10, poseCallback);// 循环等待回调函数ros::spin();return 0;
}
配置CMakeLists.txt
nano ~/catkin_workspace/src/learning_topic/CMakeLists.txt
在Build内,Install前加入
add_executable(pose_subscriber src/pose_subscriber.cpp)
target_link_libraries(pose_subscriber ${catkin_LIBRARIES})
编译并运行发布者
cd ~/catkin_workspace
catkin_make# 新建一个终端
source ~/catkin_workspace/devel/setup.bash
roscore
# 新建一个终端
source ~/catkin_workspace/devel/setup.bash
rosrun turtlesim turtlesim_node
# 新建一个终端
source ~/catkin_workspace/devel/setup.bash
rosrun learning_topic velocity_publisher# 新建一个终端
source ~/catkin_workspace/devel/setup.bash
rosrun learning_topic pose_subscriber# 新建一个终端
source ~/catkin_workspace/devel/setup.bash
rqt_graph
python
创建并编写脚本
nano ~/catkin_workspace/src/learning_topic/scripts/pose_subscriber.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-########################################################################
#### Copyright 2020 GuYueHome (www.guyuehome.com). ###
######################################################################### 该例程将订阅/turtle1/pose话题,消息类型turtlesim::Poseimport rospy
from turtlesim.msg import Posedef 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,注册回调函数poseCallbackrospy.Subscriber("/turtle1/pose", Pose, poseCallback)# 循环等待回调函数rospy.spin()if __name__ == '__main__':pose_subscriber()
运行
sudo chmod +x ~/catkin_workspace/src/learning_topic/scripts/pose_subscriber.py# 新建一个终端
source ~/catkin_workspace/devel/setup.bash
roscore
# 新建一个终端
source ~/catkin_workspace/devel/setup.bash
rosrun turtlesim turtlesim_node
# 新建一个终端
source ~/catkin_workspace/devel/setup.bash
rosrun learning_topic velocity_publisher.py# 新建一个终端
source ~/catkin_workspace/devel/setup.bash
rosrun learning_topic pose_subscriber.py# 新建一个终端
source ~/catkin_workspace/devel/setup.bash
rqt_graph