【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.
}
相关推荐
宵时待雨1 小时前
linux笔记归纳25:多路转接epoll
linux·服务器·网络·c++
Frank_refuel1 小时前
【C++项目】手撕JRpc框架(单机怎么优化到分布式思想)
开发语言·c++
ShineWinsu1 小时前
对于Redis:Hash类型的解析
c++·redis·分布式·缓存·面试·hash·哈希表
wuminyu1 小时前
JEP491中synchronized关键字引发的平台线程钉住解决方法简介
java·linux·c语言·jvm·c++
All for pursuit.1 小时前
【贪心-4】581.最短无序连续子数组
数据结构·c++·算法·leetcode
无名猿2 小时前
list 与 forward_list:链表真的比 vector 快吗
c++·性能优化·stl·内存管理·标准库
笑鸿的学习笔记2 小时前
C++笔记之SIMD与SSE指令集
开发语言·c++·笔记
汉克老师2 小时前
GESP2026年9月认证C++一级( 第二部分判断题(1~10题)精讲
c++·gesp·小学生·学c++编程
一只旭宝3 小时前
C++ 后端开发面试题整理
java·c++·面试
xlq223223 小时前
全面复习1
c++