init
This commit is contained in:
41
protocol_ws/cpp_prococol/src/cpp_sub_topic.cpp
Normal file
41
protocol_ws/cpp_prococol/src/cpp_sub_topic.cpp
Normal file
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
本程序为 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;
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user