【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.
}
相关推荐
不是杠杠几秒前
驼峰命名法(Camel Case)与匈牙利命名法(Hungarian Notation)详解
c++
Epiphany.5569 分钟前
基于c++的LCA倍增法实现
c++·算法·深度优先
落羽的落羽9 分钟前
【落羽的落羽 C++】vector
c++
newki32 分钟前
学习笔记,Linux虚拟机中C/C++的编译相关流程步骤
c语言·c++
jerry6091 小时前
c++流对象
开发语言·c++·算法
虾球xz1 小时前
游戏引擎学习第247天:简化DEBUG_VALUE
c++·学习·游戏引擎
superior tigre2 小时前
C++学习:六个月从基础到就业——模板编程:模板特化
开发语言·c++·学习
码农新猿类2 小时前
信号量函数
linux·c++·visual studio
·醉挽清风·2 小时前
学习笔记—双指针算法—移动零
c++·笔记·学习·算法
Ayanami_Reii3 小时前
Leetcode837.新21点
c++·笔记·算法