一、jiffies定时器,HZ=100,精度只能达到10ms。
注:采用jiffies+msecs_to_jiffies(xx ms);可做到ms级,不过精度不够
#include
#include
static struct timer_list ms_timer;//DO-->定义timer_list结构体
static void ms_timer_handler(void)//DO-->定义定时器处理函数
{
printk("DO_DEBUG----------->%s\n",__func__);
// ms_timer.expires=jiffies+HZ;
ms_timer.expires=jiffies+msecs_to_jiffies(10);
ms_timer.function=&ms_timer_handler;
add_timer(&ms_timer);
}
static int32_t xxx_init(void)
{
// hrtimer_init_module();
init_timer(&ms_timer); //DO-->初始化定时器
ms_timer.expires=jiffies+msecs_to_jiffies(10); //DO-->定义中断时间:10ms进入中断
//ms_timer.expires=jiffies+HZ;
//ms_timer.data=(unsigned long)ms_timer;//区分不同定时器,未验证
ms_timer.function=&ms_timer_handler; //DO-->定义定时器中断处理函数
add_timer(&ms_timer); //DO-->增加注册定时器,使定时器生效
}
二、hrtimer高精度定时器,可做到ns级,此处做到毫秒如下例:
注:实际是为纳秒级,由此处ktime_set(const long secs, const unsigned long nsecs)决定的,参数下此处参数即可实现纳秒级。
#include
#include
#include
#define KER_PRINT(fmt, ...) printk("
static struct hrtimer vibe_timer;
static struct work_struct vibe_work;
static int value = 2000; /*注:以毫秒ms为单位 Time out setting,2 seconds */
static enum hrtimer_restart vibrator_timer_func(struct hrtimer *timer) //DO-->回调函数,中断时调用
{
struct timespec uptime;
do_posix_clock_monotonic_gettime(&uptime);
KER_PRINT("Time:%lu.%02lu\n",
(unsigned long) uptime.tv_sec,
(uptime.tv_nsec / (NSEC_PER_SEC / 1000)));
KER_PRINT("vibrator_timer_func\n");
schedule_work(&vibe_work);
return HRTIMER_NORESTART;
}
static void vibe_work_func(struct work_struct *work) //DO-->工作队列函数
{
KER_PRINT("'vibe_work_func'-->work\n");
// msleep(50); /* CPU sleep */
vibe_timer.function = vibrator_timer_func;
hrtimer_start(&vibe_timer,
ktime_set(value / 1000, (value % 1000) * 1000000),HRTIMER_MODE_REL);
}
static void ker_driver_init(void) //DO-->hrtimer高精度定时器初始化函数
{
struct timespec uptime;
KER_PRINT("ker_driver_init\n");
hrtimer_init(&vibe_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); //DO-->hrtimer定时器初始化
vibe_timer.function = vibrator_timer_func; //DO-->hrtimer定时器回调函数
hrtimer_start(&vibe_timer,
ktime_set(value / 1000, (value % 1000) * 1000000),HRTIMER_MODE_REL); //DO-->hrtimer定时器时间初始化,其中ktime_set(秒,纳秒)
do_posix_clock_monotonic_gettime(&uptime); //线程建立时间,用于比较看(定时器)此时时间
KER_PRINT("Time:%lu.%02lu\n",
(unsigned long) uptime.tv_sec,
(uptime.tv_nsec / (NSEC_PER_SEC / 1000)));
INIT_WORK(&vibe_work, vibe_work_func); /* Intialize the work queue */ //初始化工作队列
}
static int32_t xxxx_init(void)
{
ker_driver_init();
....
}