一、内核为高精度定时器重新设计了一套软件架构,它可以为我们提供纳秒级的定时精度,以满足对精确时间有迫切需求的应用程序或内核驱动,以下学习使用hrtimer(high resolution timer)高精度定时器。
二、hrtimer_init函数初始化定时器工作模式。which_clock可以是CLOCK_REALTIME、CLOCK_MONOTONIC、CLOCK_BOOTTIME中的一种,mode则可以是相对时间HRTIMER_MODE_REL,也可以是绝对时间HRTIMER_MODE_ABS。
void hrtimer_init(struct hrtimer *timer, clockid_t which_clock,
enum hrtimer_mode mode);
三、设定超时回调函数。
timer.function = hr_callback;
四、使用hrtimer_start激活该定时器。根据time和mode参数的值计算hrtimer的超时时间,并设置到timer->expire域。 expire设置的是绝对时间,所以如果参数mode的值为HRTIMER_MODE_REL(即参数tim的值为相对时间),那么需要将tim的值修正为绝对时间:expire = tim + timer->base->get_time(),调用enqueue_hrtimer,将hrtimer加入到红黑树中。
int hrtimer_start(struct hrtimer *timer, ktime_t tim,
const enum hrtimer_mode mode);
五、使用hrtimer_cancel取消一个hrtimer。
int hrtimer_cancel(struct hrtimer *timer);
六、定时器一旦到期,function字段指定的回调函数会被调用,该函数的返回值为一个枚举值,它决定了该hrtimer是否需要被重新激活。
enum hrtimer_restart {
HRTIMER_NORESTART, /* Timer is not restarted /
HRTIMER_RESTART, / Timer must be restarted */
};
七、把hrtimer的到期时间推进一个tick周期,返回HRTIMER_RESTART表明该hrtimer需要再次启动,以便产生下一个tick事件。
hrtimer_forward(timer, now, tick_period);
return HRTIMER_RESTART;
示例为模拟pwm波
形控制占空比调节风扇的速度
/*
* linux/drivers/video/backlight/dc_fan.c
* direct current fan driver
*/
#include <linux/kernel.h>
#include <linux/gpio.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_gpio.h>
#include <linux/of_platform.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/sched.h>
#include <linux/pm.h>
#include <linux/sysctl.h>
#include <linux/proc_fs.h>
#include <linux/platform_device.h>
#include <asm/uaccess.h>
#include <asm/io.h>
#include <linux/delay.h>
#include <linux/hrtimer.h>
#include <linux/jiffies.h>
#include <linux/miscdevice.h>
#define GPIO_HIGH 1
#define GPIO_LOW 0
int FAN_OUT_GPIO;
int FAN_EN_GPIO;
int fan_freq=1000; //1000-1Khz
int duty_cycle=40;
int temp;
static struct hrtimer dc_timer;
ktime_t kt;
ssize_t dcfan_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos)
{
int ret;
char *data;
char *first,*second;
printk(KERN_EMERG "%s,line:%d\n",__FUNCTION__,__LINE__);
if(!copy_from_user(