Files
ROS2_WS/protocol_ws/cpp_prococol/src/cpp_sub_topic.cpp
2026-02-12 20:56:30 +08:00

41 lines
1.4 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
本程序为 ROS2 订阅话题的示例代码,订阅话题,当有消息的时候,打印出来
*/
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp" // 包含字符串消息类型的头文件
using StringMsg = std_msgs::msg::String; // 定义一个别名,方便后续使用
class MinimalSubscriber : public rclcpp::Node
{
public:
MinimalSubscriber() : Node("minimal_subscriber") // 构造函数,初始化节点名称
{
// 创建一个订阅者对象,订阅"chatter"主题使用默认QoS设置并绑定回调函数
subscription_ = this->create_subscription<StringMsg>(
"chatter",10,std::bind(&MinimalSubscriber::topic_callback, this, std::placeholders::_1)
);
}
// 订阅回调函数,接收消息并打印
void topic_callback(const StringMsg::SharedPtr msg)
{
RCLCPP_INFO(this->get_logger(), "Subscriber: '%s'", msg->data.c_str()); // 打印日志,显示接收到的消息内容
}
private:
rclcpp::Subscription<StringMsg>::SharedPtr subscription_; // 订阅者对象
};
int main(int argc, char *argv[])
{
rclcpp::init(argc, argv); // 初始化ROS2客户端库
auto node = std::make_shared<MinimalSubscriber>(); // 创建订阅者节点对象
rclcpp::spin(node); // 进入循环,等待回调函数被调用
rclcpp::shutdown(); // 关闭ROS2客户端库
return 0;
}