全球最实用的IT互联网信息网站!

AI人工智能P2P分享&下载搜索网页发布信息网站地图

当前位置:诺佳网 > 电子/半导体 > 嵌入式技术 >

Linux高精度定时器hrtimer使用示例

时间:2023-10-04 15:38

人气:

作者:admin

标签: 定时器  函数 

导读:低分辨率定时器是用jiffies来定时的,所以会受到HZ影响,如果HZ为200,代表每秒种产生200次中断,那一个jiffies就需要5毫秒,所以精度为5毫秒。 如果精度需要达到纳秒级别,则需要使用...

低分辨率定时器是用jiffies来定时的,所以会受到HZ影响,如果HZ为200,代表每秒种产生200次中断,那一个jiffies就需要5毫秒,所以精度为5毫秒。

如果精度需要达到纳秒级别,则需要使用高精度定时器hrtimer。

使用示例

单次定时

加载驱动一秒后输出“hrtimer handler”:

#include < linux/init.h >
#include < linux/kernel.h >
#include < linux/module.h >

#include < linux/ktime.h >
#include < linux/hrtimer.h >

static struct hrtimer timer;

static enum hrtimer_restart timer_handler(struct hrtimer *timer )
{
 printk("hrtimer handlern");
    
    return HRTIMER_NORESTART;
}

static int __init my_init(void) 
{
    ktime_t tim;
    
    hrtimer_init(&timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
    timer.function = timer_handler;
    tim = ktime_set(1,0); //1s
    hrtimer_start(&timer,tim,HRTIMER_MODE_REL);

    return 0;
}

static void __exit my_exit(void)
{
 printk("%s entern", __func__);
 hrtimer_cancel(&timer);
}

module_init(my_init);
module_exit(my_exit);
MODULE_LICENSE("GPL");

循环定时

循环定时可以在回调函数中调用hrtimer_forward_now()重新设置定时时间,然后将返回值设置为HRTIMER_RESTART代表重启定时器,就可以做到循环定时的效果。

每隔一秒输出“hrtimer handler”:

#include < linux/init.h >
#include < linux/kernel.h >
#include < linux/module.h >

#include < linux/ktime.h >
#include < linux/hrtimer.h >

static struct hrtimer timer;

static enum hrtimer_restart timer_handler(struct hrtimer *timer )
{
    printk("hrtimer handlern");
    
    hrtimer_forward_now(timer, ktime_set(1,0));//重新设置定时时间
    
    return HRTIMER_RESTART;//重启定时器
}

static int __init my_init(void) 
{
    ktime_t tim;
    
    hrtimer_init(&timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
    timer.function = timer_handler;
    tim = ktime_set(1,0); //1 s
    hrtimer_start(&timer,tim,HRTIMER_MODE_REL);

    return 0;
}

static void __exit my_exit(void)
{
    printk("%s entern", __func__);
    hrtimer_cancel(&timer);
}

module_init(my_init);
module_exit(my_exit);
MODULE_LICENSE("GPL");
温馨提示:以上内容整理于网络,仅供参考,如果对您有帮助,留下您的阅读感言吧!
相关阅读
本类排行
相关标签
本类推荐

CPU | 内存 | 硬盘 | 显卡 | 显示器 | 主板 | 电源 | 键鼠 | 网站地图

Copyright © 2025-2035 诺佳网 版权所有 备案号:赣ICP备2025066733号
本站资料均来源互联网收集整理,作品版权归作者所有,如果侵犯了您的版权,请跟我们联系。

关注微信