【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.
}
相关推荐
jojo_zjx2 分钟前
GESP 25年6月2级 幂和数
c++
计算机毕业设计开发2 分钟前
django高校公寓管理系统--附源码64226
java·c++·spring boot·python·spring cloud·django·php
睡不醒的kun4 分钟前
不定长滑动窗口-基础篇(2)
数据结构·c++·算法·leetcode·哈希算法·散列表·滑动窗口
vegetablesssss16 分钟前
=和{}赋值区别
c++
dyyx11116 分钟前
C++编译期数据结构
开发语言·c++·算法
曼巴UE516 分钟前
UE C++ 组件 非构造函数创建的技巧
开发语言·c++
2301_7903009625 分钟前
C++中的观察者模式实战
开发语言·c++·算法
坐怀不乱杯魂30 分钟前
Linux - 线程的同步与互斥
linux·c++
HABuo31 分钟前
【linux基础I/O(一)】文件系统调用接口&文件描述符详谈
linux·运维·服务器·c语言·c++·ubuntu·centos
2401_8914504637 分钟前
基于C++的游戏引擎开发
开发语言·c++·算法