Programming implementation of subscriber
1 Introduction
In the previous article ("ROS Study Notes (3) - Programming Implementation of Publisher"), how to use c++ publishes a topic to achieve circular motion of the little turtle. The programming of subscribers is similar to that of publishers. Before reading this article, it is recommended to read the previous article first.
2. Model
3. Programming
Similar to the previous lecture, create a cpp file in/catkin_ws/src/learning_topic/src
. The code is below.
/**
* 该例程将订阅/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;
}
Similarly, add the following code to CMakeLists
, directly above Install
:
add_executable(pose_subscriber src/pose_subscriber.cpp)
target_link_libraries(pose_subscriber ${
catkin_LIBRARIES})
In the same way, compile the function package, set the environment variables, and run the turtle simulation node.
When the turtle has not moved, try running subscriber. It is expected that the returned parameters should not change:
rosrun learning_topic pose_subscriber
We now try to use the publisher program written in the previous article to make the turtle move and see the changes in the parameters returned by the subscriber:
rosrun learning_topic velocity_publisher
Or use
$ rosrun turtlesim turtle_teleop_key
keyboard control commands to control the movement of the turtle.
It can be seen that the parameters fed back by the subscriber have indeed changed.