【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.
}
相关推荐
愚者游世42 分钟前
力扣解决二进制 | 题型常用知识点梳理
c++·程序人生·算法·leetcode·职场和发展
蜡笔小马1 小时前
15.Boost.Geometry 坐标系统详解
c++·boost
AD钙奶-lalala1 小时前
Android编译C++代码步骤详解
android·开发语言·c++
rhett. li2 小时前
FreeBSD系统中使用clang/clang++编译Skia源码的方法
c++·ui·用户界面
_风华ts2 小时前
C++函数指针
c++·函数指针
威桑2 小时前
解决 Qt6 程序 在Linux 环境下无法输入中文的问题
linux·c++·qt
浅念-3 小时前
C++ :类和对象(4)
c语言·开发语言·c++·经验分享·笔记·学习·算法
shentuyu木木木(森)3 小时前
栈与队列基础
c++··队列
yuuki2332333 小时前
【C++】模拟实现 AVL树
java·c++·算法
蜡笔小马4 小时前
20.Boost.Geometry 中常用空间算法详解:crosses、densify、difference 与离散距离度量
c++·算法·boost