ROS与C++入门教程-Timers(定时器)
说明:
介绍roscpp的定时器的使用
定时器
roscpp的定时器会计划在某一速率下执行一次回调操作,在订阅或服务中的回调函数队列机制中使用。
定时器不是实时的线程/内核替换,而是对那些没有硬实时要求的东西有用。
创建定时器
通过ros::NodeHandle::createTimer()方法创建
代码示例:
ros::Timer timer = nh.createTimer(ros::Duration(0.1), timerCallback);
createTimer()方法有多种不同的形式,可以让你指定不同的参数项和回调函数类型
一般用法:
ros::Timer ros::NodeHandle::createTimer(ros::Duration period, , bool oneshot = false);
函数说明:
period ,这是调用定时器回调函数时间间隔。例如,ros::Duration(0.1),即每十分之一秒执行一次
,回调函数,可以是函数,类方法,函数对象。
oneshot ,表示是否只执行一次,如果已经执行过,还可以通过stop()、setPeriod(ros::Duration)和start()来规划再执行一次。
回调函数用法
回调函数用法:
void callback(const ros::TimerEvent&);
ros::TimerEvent结构体作为参数传入,它提供时间的相关信息,对于调试和配置非常有用
ros::TimerEvent结构体说明:
ros::Time last_expected 上次回调期望发生的时间
ros::Time last_real 上次回调实际发生的时间
ros::Time current_expected 本次回调期待发生的时间
ros::Time current_real 本次回调实际发生的时间
ros::WallTime profile.last_duration 上次回调的时间间隔(结束时间-开始时间),是wall-clock时间。
回调函数类型:
roscpp 支持所有boost::bind类型的回调:
functions
class methods
functor objects (包含boost::function)
Functions函数:
代码示例:
void callback(const ros::TimerEvent& event)
{
...
}
...
ros::Timer timer = nh.createTimer(ros::Duration(0.1), callback);
Class Methods类方法:
代码示例:
void Foo::callback(const ros::TimerEvent& event)
{
...
}
...
Foo foo_object;
ros::Timer timer = nh.createTimer(ros::Duration(0.1), &Foo::callback, &foo_object);
Functor Objects函数对象:
class Foo
{
public:
void operator()(const ros::TimerEvent& event)
{
...
}
};
...
ros::Timer timer = nh.createTimer(ros::Duration(0.1), Foo());
传递到createTimer()Functor必需是copyable的
Wall-clock Timers
ros::Timer使用ROS Clock
如果想要定时器使用wall-clock时间,可以替代Timer为WallTimer
代码示例:
void callback(const ros::WallTimerEvent& event)
{
...
}
...
ros::WallTimer timer = nh.createWallTimer(ros::WallDuration(0.1), callback);