依照海龟仿真器的话题模型,ROS Master 控制发布者和订阅者两个节点,话题类型是海龟的位姿信息,通过这一途径,message从发布者传输到订阅者。这篇学习主要旨在实现订阅者的功能。
如何实现一个订阅者
- 初始化ROS节点(init,同时创建节点句柄:同一个cpp程序下创建的都是同一个节点的句柄);
- 订阅需要的话题(创建subscriber对象,调用subscribe子函数订阅相关话题topic,并且注册回调函数);
- 循环等待话题消息,接收到消息后进入回调函数(ros消息回调处理函数:ros::spin(),作用是主程序在接收到订阅信息的时候并不是立即处理,而是在遇到回调处理函数之后才进行处理);
- 在回调函数中完成消息处理。
同样是在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