本人在学习鱼香ROS2的过程中对代码还是有些不了解,于是把所写的代码进行解构分析其流程和逻辑,适合像我一样的初学者进行辅助学习。我们这里以c++代码为例。
一、发布者
1.cpp
发布者全部代码为:
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
class TopicPublisher01 : public rclcpp::Node
{
public:
TopicPublisher01(std::string name) : Node(name)
{
RCLCPP_INFO(this->get_logger(), "%s节点已经启动.", name.c_str());
command_publisher_=this->create_publisher<std_msgs::msg::String>("command",10);
timer_=this->create_wall_timer(std::chrono::milliseconds(500),std::bind(&TopicPublisher01::timer_callback,this));
}
private:
void timer_callback()
{
std_msgs::msg::String message;
message.data = "forward";
RCLCPP_INFO(this->get_logger(),"Publishing: '%s'",message.data.c_str());
command_publisher_->publish(message);
}
rclcpp::TimerBase::SharedPtr timer_;
rclcpp::Publisher<std_msgs::msg::String>::SharedPtr command_publisher_;
};
int main(int argc, char **argv)
{
rclcpp::init(argc, argv);
auto node = std::make_shared<TopicPublisher01>("topic_publisher_01");
rclcpp::spin(node);
rclcpp::shutdown();
return 0;
}
代码的框架为:
节点类TopicPublisher01:
继承于rclcpp::Node,表示这是一个 ROS 2 节点类
成员函数:
构造函数:初始化节点、创建定时器和发布者
timer_callback:定时触发,发布消息
成员变量:
command_publisher_:发布器,发布 std_msgs::msg::String 类型的消息
timer_:定时器,定时调用 timer_callback()
主函数:
调用 rclcpp::init 进行初始化。
创建 TopicPublisher01 节点对象。
使用 rclcpp::spin 让节点保持运行。
结束时调用 rclcpp::shutdown 关闭节点
整体流程为:
1.main函数中启动节点
2.调用构造函数创建TopicPublisher01 节点对象,名称为“topic_publisher_01”
3.创建 Publisher (发布者),名称为command,消息队列为10
4.创建 Timer (定时器),500ms进行触发
5.Timer 定时触发
6.程序终止
1.启动节点
rclcpp::init(argc, argv)
初始化 ROS 2 客户端库,解析命令行参数
2.创建节点
auto node = std::make_shared<TopicPublisher01>("topic_publisher_01");
使用make_shared来创建一个TopicPublisher01的节点,传入节点名称"topic_publisher_01',这里调用了TopicPublisher01类的构造函数TopicPublisher01(std::string name)
class TopicPublisher01 : public rclcpp::Node
{
public:
TopicPublisher01(std::string name) : Node(name)
{
RCLCPP_INFO(this->get_logger(), "%s节点已经启动.", name.c_str());
command_publisher_=this->create_publisher<std_msgs::msg::String>("command",10);
timer_=this->create_wall_timer(std::chrono::milliseconds(500),std::bind(&TopicPublisher01::timer_callback,this));
}
进入构造函数后,使用RCLCPP_INFO函数,用于将日志消息输出到终端,我们就能在命令行中


8855

被折叠的 条评论
为什么被折叠?



