【ROS1转ROS2示例】

ROS1中的代码:

这是一个循环函数:

cpp 复制代码
ros::Rate loop_rate(10); // Adjust the publishing rate as needed
		while (ros::ok())
		{
			loop_rate.sleep();
		}

如果转ROS2,可以使用rclcpp::WallRate或者直接依赖于执行器(Executor)的循环来实现类似的功能。这里提供两种方法:

方法一:使用rclcpp::WallRate

objectivec 复制代码
rclcpp::WallRate loop_rate(10Hz); // Adjust the rate as needed
while (rclcpp::ok()) { // Replaced ros::ok() with rclcpp::ok()
    loop_rate.sleep();
}

方法2: 利用执行器(Executor)的循环

如果你的节点中已经有其他需要执行的定时任务或者回调函数,使用执行器来驱动循环会更加高效且符合ROS2的设计模式。例如,使用单线程执行器(SingleThreadedExecutor):

objectivec 复制代码
rclcpp::executors::SingleThreadedExecutor executor;
executor.add_node(node); // Assuming 'node' is your rclcpp::Node

while (rclcpp::ok()) {
    executor.spin_once(std::chrono::milliseconds(100)); // Adjust the duration as needed
    // This will call available callbacks and then sleep for the specified duration.
}
相关推荐
码匠许师傅6 小时前
【设计模式精讲】29.行为型模式总结与对比(Behavioral Patterns Summary)
c++·设计模式·uml
啦啦啦啦啦zzzz7 小时前
Logger的组装(c++20)
c++·算法·c++20
繁星蓝雨8 小时前
C++的设计与演进大纲(如何从C语言一步步成长为C++)
c语言·开发语言·c++·c++历史·c++演进
蒸蒸yyyyzwd8 小时前
机试学习笔记
c++·求职招聘
handler0110 小时前
【Linux】线程与虚拟内存的底层世界
linux·运维·服务器·c++·线程·虚拟地址空间·共享内存
郝学胜-神的一滴10 小时前
C++11 工程级应用 09:告别无谓拷贝,解锁高性能移动语义
开发语言·数据结构·c++·vscode·软件工程·visual studio
hetao173383712 小时前
校内场-提高组 ZYZSC-S-Round 4
c++·算法
stellanke12 小时前
Linux网络编程实战2:TCP Socket 基础与实践
linux·网络·c++
蒸蒸yyyyzwd13 小时前
机试和Redis学习笔记
c++·笔记·面试
tdtsmt13 小时前
2026年SMT贴片加工选型指南:天地通电子推荐参考
c++