ROS学习笔记4_订阅者Subscriber

 依照海龟仿真器的话题模型,ROS Master 控制发布者和订阅者两个节点,话题类型是海龟的位姿信息,通过这一途径,message从发布者传输到订阅者。这篇学习主要旨在实现订阅者的功能。

如何实现一个订阅者

  1. 初始化ROS节点(init,同时创建节点句柄:同一个cpp程序下创建的都是同一个节点的句柄);
  2. 订阅需要的话题(创建subscriber对象,调用subscribe子函数订阅相关话题topic,并且注册回调函数);
  3. 循环等待话题消息,接收到消息后进入回调函数(ros消息回调处理函数:ros::spin(),作用是主程序在接收到订阅信息的时候并不是立即处理,而是在遇到回调处理函数之后才进行处理);
  4. 在回调函数中完成消息处理。

同样是在src文件下下创建订阅者相关的cpp文件

/*
	This program will subscribe topic /turtle1/pose, message type turtlesim::Pose
*/

#include<ros/ros.h>
#include<turtlesim/Pose.h>

//Go to the "message call back function" after receiving the subscribing message
void poseCallback(const turtlesim::Pose::ConstPtr& msg)
{
	//Print the received message
	ROS_INFO("Turtle pose: x:%0.6f, y:%0.6f",msg->x,msg->y);
}

int main(int argc, char **argv)
{
	//initiate the ros node
	ros::init(argc, argv, "pose_subscriber");
	
	//create the node handle
	ros::NodeHandle n;
	
	//create a subscriber, subscribes the topic named /turtle1/pose, registers the call back function
	ros::Subscriber pose_sub = n.subscribe("/turtle1/pose", 10, poseCallback);
	
	//waiting for call back function
	ros::spin();
	
	return 0;
}

同之前创建Publisher相同,要在CMakeList.txt中添加这个C++文件的编译规则。

  • 设置需要编译的代码和生成的可执行文件
  • 设置链接库
add_executable(pose_subscriber src/pose_subscriber.cpp)
target_link_libraries(pose_subscriber ${catkin_LIBRARIES})

 回到cankin_ws目录下使用make指令编译cpp文件。

启动海龟仿真器,先使用之前编写的发布者文件让海龟动起来,然后再启动订阅者节点去返回海龟的位置信息。

roscore

rosrun turtlesim turtlesim_node

rosrun learing_topic velocity_publisher

rosrun learing_topic pose_subscriber

 

也可用键盘控制节点来移动海龟的位置。

rosrun turtlesim turtle_teleop_key

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值