【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.
}
相关推荐
漫雾_3 小时前
两个强制结束进程的方法
c++·驱动开发·安全
HAPPY酷3 小时前
C++ 多线程实战三板斧
java·开发语言·c++·技术美术
fpcc3 小时前
并行编程实战——CUDA编程的Tile
c++·cuda
_风华ts5 小时前
C++ 函数封装与绑定
c++·函数指针·函数封装
ShineWinsu5 小时前
对于C++中stack和queue的详细介绍
开发语言·数据结构·c++·面试·stl·queue·stack
L_Aria5 小时前
6421. 【NOIP2019模拟11.11】匹配
c++·算法·动态规划
智者知已应修善业6 小时前
【PAT乙级真题解惑1012数字分类】2025-3-29
c语言·c++·经验分享·笔记·算法
-To be number.wan7 小时前
算法学习日记 | 双指针
c++·学习·算法
wangluoqi7 小时前
c++ 逆元 小总结
开发语言·c++
瓦特what?7 小时前
插 入 排 序
开发语言·c++