一、Time
1、时刻ros::Time 和间隔ros::Duration
统一表示形式:int32 sec int32 nsec
获得当前时间:ros::Time begin = ros::Time::now();
创建时刻和间隔:
ros::Time a_little_after_the_beginning(0.001);
ros::Duration five_seconds(5.0);
时刻与间隔的转化:
double secs =ros::Time::now().toSec(); //时间戳转化为浮点秒
ros::Time t = ros::Time().fromSec(); //浮点转化为时间戳
ros::Duration d(0.5);
secs = d.toSec();
时刻与间隔的运算:
ros::Duration two_hours = ros::Duration(60*60) + ros::Duration(60*60);
ros::Duration one_hour = ros::Duration(2*60*60) - ros::Duration(60*60);
ros::Time tomorrow = ros::Time::now() + ros::Duration(24*60*60);
ros::Duration negative_one_day = ros::Time::now() - tomorrow;
2、Sleeping and Rates
睡眠0.5s: ros::Duration::sleep();
频率10Hz:
ros::Rate r(10);
while (ros::ok())
{
//do some work
r.sleep();
}
Rate和Timer的作用一样,最好使用Timer来定时.
二、Timer
1、使用定时器
创建定时器:
回调函数为一般函数: ros::Timer timer = n.createrTimer(ros::Duration(0.1), timerCallback);
回调函数为类成员: ros::Timer timer = n.createrTimer(ros::Duration(0.1), &class::timerCallback, &class_instance);
完整定义:
ros::Timer ros::NodeHandle::createTimer(ros::Duration period, <callback>, bool oneshot = false);
oneshot为false表示连续定时,true表示只定时一次.默认为false.
回调函数:
void timerCallback( const ros::TimerEvent &event );
2、回调特征
struct TimerEvent
{
Time last_expected; ///< 上一回调函数应该发生的时刻
Time last_real; ///< 上一回调函数实际发生的时刻
Time current_expected; ///< 当前回调函数应该发生的时刻
Time current_real; ///< 当前回调函数实际发生的时刻
struct
{
WallDuration last_duration; ///<包含上一回调的时间间隔(结束时间-开始时间),它始终在 `wall-clock time`
} profile;
};