pose_subscriber.cpp
//创建订阅者代码(C++)
/**
* 该例程将订阅/turtle/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;
}
如何实现一个订阅者
- 初始化ROS节点
- 订阅需要的话题
- 循环等待话题消息,接收到消息后进入回调函数
- 在回调函数中完成消息处理
存放位置:
===================================
配置订阅者代码编译规则
如何配置CMakeList.txt中的编译规则
- 设置需要编译的代码和生成的可执行文件
- 设置链接库
## Declare a C++ executable
##With catkin_make all packages are built within a single CMake context
## The recommended prefix ensures that target names across packages don't collide
# add_executable(${PROJECT_NAME}_node src/learning_topic_node.cpp)
## Specify libraries to link a library or executable target against
# target_link_libraries(${PROJECT_NAME}_node
# ${catkin_LIBRARIES}
# )
add_executable(velocity_publisher src/velocity_publisher.cpp)
target_link_libraries(velocity_publisher ${catkin_LIBRARIES})
add_executable(pose_subscriber src/pose_subscriber.cpp)
target_link_libraries(pose_subscriber ${catkin_LIBRARIES})
在catkin_ws文件夹下进行catkin_make
============================
编译并运行订阅者
cd ~/catkin_ws
catkin_make
source devel/setup.bash
roscore
rosrun turtlesim turtlesim_node
rosrun learning_topic pose_subscirber
让小海龟动起来,就会不断刷新位置