0. 写于最前面
但愿你们收藏:html
本文持续更新地址:https://haoqchen.site/2018/11/08/ROS-time/api
本文总结了一些ROS中经常使用到的时间相关的一些类、定时器、概念等。app
做者会长期更新本身学到的一些知识,有什么错误但愿你们可以一块儿探讨,一块儿进步。喜欢的话点个赞呗。函数
左侧专栏还在更新其余ROS实用技巧哦,关注一波?ui
1. 概述
roslib给用户提供了ros::Time and ros::Duration两个类来描述时刻以及时间间隔两个概念,其中Duration能够是负数。Time和Duration拥有同样的成员:
int32 sec
int32 nsecthis
通常状况下,这里的时间都是跟平台(即系统)的时间相关联的,但ROS提供了一种模拟时钟即ROS时钟时间,当进行了相应设置时,这里的时间就是ROS时钟时间。spa
2. 时间与时间间隔的基本使用
2.1 得到当前时间
ros::Time begin = ros::Time::now();
注:若是使用的是模拟时间,now在/clock话题接收到第一个消息以前都会返回0ssr
2.2 定义类对象
ros::Time::Time(uint32_t _sec, uint32_t _nsec)
ros::Time::Time(double t)code
ros::Duration::Duration(uint32_t _sec, uint32_t _nsec)
ros::Duration::Duration(double t)htm
_sec是秒,_nsec是纳秒
故ros::Time a_little_after_the_beginning(0, 1000000);等价于ros::Time a_little_after_the_beginning(0.001);
2.3 相互转化、比较
Time继承自
template<class T, class D>
class ros::TimeBase< T, D >
Duration继承自
template<class T>
class ros::DurationBase< T >
两个基类都实现了>、<、!=等比较符。而且二者都实现了
uint64_t toNSec () const
double toSec () const
咱们能够经过这两个函数来进行Time和Duration的转化
2.4 运算符
两个基类都重载了+、-、+=、-=运算符:
1 hour + 1 hour = 2 hours (duration + duration = duration)
2 hours - 1 hour = 1 hour (duration - duration = duration)
Today + 1 day = tomorrow (time + duration = time)
Today - tomorrow = -1 day (time - time = duration)
Today + tomorrow = error (time + time is undefined)
3. 延时与循环
bool ros::Duration::sleep() ros::Duration(0.5).sleep(); // sleep for half a second
4. 定时器
ros::Timer
首先须要说明的是,ROS并非实时系统,因此定时器并不能确保精肯定时。精确的执行时间以及理论上应该执行的时间能够在回调函数的ros::TimerEvent结构中获得。
ros::Timer ros::NodeHandle::createTimer(ros::Duration period, <callback>, bool oneshot = false);
ros::Timer timer = n.createTimer(ros::Duration(0.1), timerCallback);//定时0.1s
void timerCallback(const ros::TimerEvent& e);
其中oneshot是定义是否只定时一次,默认连续定时。这里也不必定要回调函数,也能够传函数对象等,这里不细述。
其中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; };
ros::Rate
ros::Rate r(10); // 10 hz while (ros::ok()) { //... do some work ... bool met = r.sleep(); }
它的功能就是先设定一个频率,而后经过睡眠度过一个循环中剩下的时间,来达到该设定频率。若是可以达到该设定频率则返回true,不能则返回false。
计时的起点是上一次睡眠的时间、构造函数被调用、或者调用void ros::Rate::reset()函数重置时间。
由于没有TimerEvent,因此相对于Timer而言,Rate的精确度会有所降低。
参考
http://wiki.ros.org/roscpp/Overview/Time
http://wiki.ros.org/roscpp_tutorials/Tutorials/Timers
http://docs.ros.org/diamondback/api/rostime/html/classros_1_1Rate.html