摘要:节点(Node)是通过 ROS 图进行通信的可执行进程。
本文分享自华为云社区《编写一个简单的发布者和订阅者》,作者: MAVER1CK 。
@[toc]
参考官方文档:Writing a simple publisher and subscriber (C++)
背景
节点(Node)是通过 ROS 图进行通信的可执行进程。 在本教程中,节点将通过话题(Topic)以字符串消息的形式相互传递信息。 这里使用的例子是一个简单的“talker”和“listener”系统; 一个节点发布数据,另一个节点订阅该话题,以便它可以接收该数据。 可以在此处找到这些示例中使用的代码。
1.创建一个包
打开一个新的终端然后source你的ROS 2安装,以便ros2命令可以正常使用:
source /opt/ros/humble/setup.bash
回顾一下,包应该在src目录下创建,而不是在工作区的根目录下。因此,接下来,cd到ros2_ws/src,并运行包创建命令。
ros2 pkg create --build-type ament_cmake cpp_pubsub
你的终端将返回一条信息,验证你的cpp_pubsub包及其所有必要的文件和文件夹的创建。
cd到ros2_ws/src/cpp_pubsub/src。回顾一下,这是任何CMake包中包含可执行文件的源文件所在的目录。
2.编写发布者节点
下载示例代码:
wget -O publisher_member_function.cpp https://raw.githubusercontent.com/ros2/examples/humble/rclcpp/topics/minimal_publisher/member_function.cpp
打开之后内容如下
#include <chrono> #include <functional> #include <memory> #include <string> #include "rclcpp/rclcpp.hpp" #include "std_msgs/msg/string.hpp" using namespace std::chrono_literals; /* This example creates a subclass of Node and uses std::bind() to register a * member function as a callback from the timer. */ class MinimalPublisher : public rclcpp::Node { public: MinimalPublisher() : Node("minimal_publisher"), count_(0) { publisher_ = this->create_publisher<std_msgs::msg::String>("topic", 10); timer_ = this->create_wall_timer( 500ms, std::bind(&MinimalPublisher::timer_callback, this)); } private: void timer_callback() { auto message = std_msgs::msg::String(); message.data = "Hello, world! " + std::to_string(count_++); RCLCPP_INFO(this->get_logger(), "Publishing: '%s'", message.data.c_str()); publisher_->publish(message); } rclcpp::TimerBase::SharedPtr timer_; rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_; size_t count_; }; int main(int argc, char * argv[]) { rclcpp::init(argc, argv); rclcpp::spin(std::make_shared<MinimalPublisher>()); rclcpp::shutdown(); return 0; }
2.1 查看代码
代码的顶部包括你将要使用的标准C++头文件。在标准C++头文件之后是rclcpp/rclcpp.hpp,它允许你使用ROS 2系统中最常见的部分。最后是std_msgs/msg/string.hpp,它包括你将用于发布数据的内置消息类型。
这些行代表节点的依赖关系。 回想一下,必须将依赖项添加到 package.xml 和 CMakeLists.txt,您将在下一节中执行此操作。
#include <chrono> #include <functional> #include <memory> #include <string> #include "rclcpp/rclcpp.hpp" #include "std_msgs/msg/string.hpp" using namespace std::chrono_literals;
下一行通过继承rclcpp::Node创建节点类MinimalPublisher。代码中的每个this都是指的节点。
class MinimalPublisher : public rclcpp::Node
公共构造函数将节点命名为 minimal_publisher 并将 count_ 初始化为 0。在构造函数内部,发布者使用 String 消息类型、话题名称为 topic 以及所需的队列大小,以便在发生备份时限制消息,进行初始化。 接下来,timer_ 被初始化,这导致 timer_callback 函数每秒执行两次。
public: MinimalPublisher() : Node("minimal_publisher"), count_(0) { publisher_ = this->create_publisher<std_msgs::msg::String>("topic", 10); timer_ = this->create_wall_timer( 500ms, std::bind(&MinimalPublisher::timer_callback, this)); }
timer_callback函数是设置消息数据和实际发布消息的地方。RCLCPP_INFO宏确保每个发布的消息都被打印到控制台。
private: void timer_callback() { auto message = std_msgs::msg::String(); message.data