< >
Home » ROS与C++入门教程 » ROS与C++入门教程-使用Timers类

ROS与C++入门教程-使用Timers类

ROS与C++入门教程-使用Timers类

说明:

  • 本教程介绍了roscpp定时器,它允许您安排一个回调发生周期性。

什么是Timers(定时器)?

  • Timers能让你以一定的频率来执行
  • 他们是比ros::Rate更加灵活和有用的形式,ros::Rate在编写简单发布节点和订阅节点用到。
  • 注意:定时器不是实时的线程/内核替换,也不能保证它们的准确度,因为系统负载/功能会有很大的变化。
  • 更多可以参考: roscpp Timers overview

使用定时器

  • 创建定时器象创建订阅一样:
ros::Timer timer = n.createTimer(ros::Duration(0.1), timerCallback);
  • 回调函数:
void timerCallback(const ros::TimerEvent& e);

完整例子

  • 上面为简单的例子,这里做一个带多个定时器的例子。
  • 代码如下:
#include "ros/ros.h"

/**
 * This tutorial demonstrates the use of timer callbacks.
 */

void callback1(const ros::TimerEvent&)
{
  ROS_INFO("Callback 1 triggered");
}

void callback2(const ros::TimerEvent&)
{
  ROS_INFO("Callback 2 triggered");
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "talker");
  ros::NodeHandle n;

  /**
   * Timers allow you to get a callback at a specified rate.  Here we create
   * two timers at different rates as a demonstration.
   */
  ros::Timer timer1 = n.createTimer(ros::Duration(0.1), callback1);
  ros::Timer timer2 = n.createTimer(ros::Duration(1.0), callback2);

  ros::spin();

  return 0;
}

代码分析:

  • 代码:
ros::Timer timer1 = n.createTimer(ros::Duration(0.1), callback1);
ros::Timer timer2 = n.createTimer(ros::Duration(1.0), callback2);
  • 增加两个定时器,一个100毫秒执行一次,一个1秒执行一次。
  • 运行效果:
[ INFO] 1251854032.362376000: Callback 1 triggered
[ INFO] 1251854032.462840000: Callback 1 triggered
[ INFO] 1251854032.562464000: Callback 1 triggered
[ INFO] 1251854032.662169000: Callback 1 triggered
[ INFO] 1251854032.762649000: Callback 1 triggered
[ INFO] 1251854032.862853000: Callback 1 triggered
[ INFO] 1251854032.962642000: Callback 1 triggered
[ INFO] 1251854033.063118000: Callback 1 triggered
[ INFO] 1251854033.162221000: Callback 1 triggered
[ INFO] 1251854033.262749000: Callback 1 triggered
[ INFO] 1251854033.262864000: Callback 2 triggered
[ INFO] 1251854033.362643000: Callback 1 triggered
[ INFO] 1251854033.463158000: Callback 1 triggered

TimerEvent结构体

  • ros::TimerEvent结构体提供当前定时器的时间信息
  • 定义如下:
struct TimerEvent
{
  Time last_expected;                     ///< In a perfect world, this is when the last callback should have happened
  Time last_real;                         ///< When the last callback actually happened

  Time current_expected;                  ///< In a perfect world, this is when the current callback should be happening
  Time current_real;                      ///< This is when the current callback was actually called (Time::now() as of the beginning of the callback)

  struct
  {
    WallDuration last_duration;           ///< How long the last callback ran for, always in wall-clock time
  } profile;
};

纠错,疑问,交流: 请进入讨论区点击加入Q群

获取最新文章: 扫一扫右上角的二维码加入“创客智造”公众号


标签: ROS与C++入门教程