[ROS study notes] (4) Implementation of Subscriber Subscriber

1. Target function

Subscribers subscribe to the pose information of sea turtles.

Second, create a feature package

First create a workspace, refer to [ROS study notes] (2) Creation of workspace and function package

Then create a feature package

cd ~/catkin_ws/src
catkin_creat_pkg learning_topic roscpp rospy std_msgs geometry_msgs turtlesim

Three, create a subscriber code

Enter the src folder of the function package and create a cpp file (you can also create it directly in the graphical interface)

cd ~/catkin_ws/src/learning_topic/src
touch pose_subscriber.cpp
sudo gedit pose_subscriber.cpp

Enter the following code

/***********************************************************************
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,注册回调函数poseCallback
    ros::Subscriber pose_sub = n.subscribe("/turtle1/pose", 10, poseCallback);

    // 循环等待回调函数
    ros::spin();

    return 0;
}

Code idea:

  1. Initialize the ROS node
  2. Topics required for subscription
  3. Wait for the topic message in a loop, and enter the callback function after receiving the message
  4. Complete message processing in the callback function
    Insert picture description here

Four, configure subscriber code compilation rules

  1. Set the code to be compiled and the executable file generated

  2. Set up the link library

In Learning_topic/CMakeList.txtthe bottom of the file Build (Install above), add the following code

add_executable(pose_subscriber src/pose_subscriber.cpp)		#描述要把哪个程序文件编译成哪个可执行文件
target_link_libraries(pose_subscriber ${catkin_LIBRARIES})	#把可执行文件和库做链接

Insert picture description here

Five, compile and run the subscriber SubScriber

1. Compile
cd ~/catkin_ws
catkin_make
source devel/setup.bash

You can add a source statement at the end of the [.bash] file, so you don’t have to enter the source command in the terminal every time

sudo vim ~/catkin_ws
source /home/huffie/catkin_ws/devel/setup.bash

2. Run

Open the baby turtle simulation program, run the subscriber, and make the baby turtle move at the same time, you can see that the posture coordinates are changing in real time.

roscore
rosrun turtlesim turtlesim_node
rosrun learning_topic pose_subscriber
rosrun turtlesim turtle_teleop_key

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44543463/article/details/114044751