0. 寫於最前面
希望大家收藏:
本文持續更新地址:https://haoqchen.site/2018/11/08/ROS-time/
本文總結了一些ROS中常用到的時間相關的一些類、定時器、概念等。
作者會長期更新自己學到的一些知識,有什么錯誤希望大家能夠一起探討,一起進步。喜歡的話點個贊唄。
左側專欄還在更新其他ROS實用技巧哦,關注一波?
1. 概述
roslib給用戶提供了ros::Time and ros::Duration兩個類來描述時刻以及時間間隔兩個概念,其中Duration可以是負數。Time和Duration擁有一樣的成員:
int32 sec
int32 nsec
一般情況下,這里的時間都是跟平台(即系統)的時間相關聯的,但ROS提供了一種模擬時鍾即ROS時鍾時間,當進行了相應設置時,這里的時間就是ROS時鍾時間。
2. 時間與時間間隔的基本使用
2.1 獲得當前時間
ros::Time begin = ros::Time::now();
注:如果使用的是模擬時間,now在/clock話題接收到第一個消息之前都會返回0
2.2 定義類對象
ros::Time::Time(uint32_t _sec, uint32_t _nsec)
ros::Time::Time(double t)
ros::Duration::Duration(uint32_t _sec, uint32_t _nsec)
ros::Duration::Duration(double t)
_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