Android 驱动中的定时器timer,hrtimer,alarmtimer

这几天需要在底层驱动实现一个feature,需要用到较长时间超时,使用了内核中相关的定时器模块来操作,下面不啰嗦,直接进入范例:
一.内核驱动中常规定时器,也是使用最为广泛的定时器,使用范例如下:

#include <linux/timer.h>
sturct charger_chip {
...
	/*timer*/
	struct timer_list		ctrl_timer;
}
1.初始化
	init_timer(&chip->ctrl_timer);
	chip->ctrl_timer.data = (ulong)chip;
	chip->ctrl_timer.function = ctrl_timer_function;
	add_timer(&chip->ctrl_timer);

2.启动定时时:
mod_timer(&chip->ctrl_timer,jiffies + msecs_to_jiffies(10*60*1000));  //10min
如果需要周期性处理事件在回调函数ctrl_timer_function中再次mod_timer即可。

3.删除定时器
del_timer(&chip->ctrl_timer);
del_timer_sync(&chip->ctrl_timer); //用于多处理器平台中

以上就是驱动中最长使用的定时器使用方法了,但是这种方法在Android系统睡眠后定时器无法更新导致事件不正确。

二、高精度定时器hrtimer
高精度定时器使用范例:

#include <linux/hrtimer.h>

sturct charger_chip {
...
	/*timer*/
	ktime_t			tim;
	struct  hrtimer	ctrl_timer;
}

1.初始化
void hrtimer_init(struct hrtimer *timer, clockid_t clock_id, enum hrtimer_mode mode);
clock_id:
	CLOCK_REALTIME	//实时时间,如果系统时间变了,定时器也会变
	CLOCK_MONOTONIC	//递增时间,不受系统影响 内部还是已jiffies为单位的
mode:
	HRTIMER_MODE_ABS = 0x0,		/* 绝对模式 */  从系统开机开始算的时间
	HRTIMER_MODE_REL = 0x1,		/* 相对模式 */  设置超时时间以后才开始算的时间
	HRTIMER_MODE_PINNED = 0x02,	/* 和CPU绑定 */
	HRTIMER_MODE_ABS_PINNED = 0x02, /* 第一种和第三种的结合 */
	HRTIMER_MODE_REL_PINNED = 0x03, /* 第二种和第三种的结合 */
常用:
hrtimer_init(&chip->timer, CLOCK_MONOTONIC	, HRTIMER_MODE_REL );

2.启动定时时:
chip->tim = ktime_set(10,5);  //10s 5ns
hrtimer_start(&chip->ctrl_timer,chip->tim, HRTIMER_MODE_REL ); 

如果需要周期性处理事件在回调函数ctrl_timer_function中return HRTIMER_RESTART即可。
static enum hrtimer_restart  hrtimer_hander(struct hrtimer *timer)
{
    /* 设置下次过期时间 */

    /* 该参数将重新启动定时器 */    
    return HRTIMER_RESTART;  
}

3.删除定时器
hrtimer_cancel(&chip->ctrl_timer);

三、alarmtimer
alarm 通常是上层设置,但是其实安卓kernel中也可以设置alarm来唤醒系统。使用范例如下:

#include <linux/alarmtimer.h>

sturct charger_chip {
...
	/*timer*/
	struct  alarm	ctrl_timer;
}

1.初始化
	alarm_init(&chip->ctrl_timer, ALARM_BOOTTIME,ctrl_timer_function);

2.启动定时时:
ararm_start_relative(&chip->ctrl_timer,ms_to_ktime(10*60*1000));  //10min
如果需要周期性处理事件在回调函数ctrl_timer_function中return ALARMTIMER_RESTART即可。

3.删除定时器
alarm_cancel(&chip->ctrl_timer);
发布了27 篇原创文章 · 获赞 18 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_24622489/article/details/87202403