【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 小时前
iceoryx编译和验证
linux·c++·零拷贝·iceoryx
王老师青少年编程1 小时前
2020年信奥赛C++提高组csp-s初赛真题及答案解析(阅读程序第2题)
c++·题解·真题·初赛·信奥赛·csp-s·提高组
你的冰西瓜2 小时前
C++ STL算法——排序和相关操作
开发语言·c++·算法·stl
今儿敲了吗2 小时前
29| 高考志愿
c++·笔记·学习·算法
浅念-3 小时前
C++ 模板进阶
开发语言·数据结构·c++·经验分享·笔记·学习·模版
紫陌涵光3 小时前
77. 组合
c++·算法·leetcode·深度优先
肆忆_5 小时前
Day 04|线程安全引用计数:让 SharedPtr 支持并发拷贝/析构
c++
三水彡彡彡彡5 小时前
C++拷贝函数:const与引用的高效实践
开发语言·c++
D_evil__6 小时前
【Effective Modern C++】第七章 并发API:35. 优先考虑基于任务的编程而非基于线程的编程
c++