RV1126 定时的驱动程序

发布于 2024-07-25  54 次阅读


  我们期望一个驱动程序可以间隔一秒钟完成一次自加和print。我们通过如下方式来实现:

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/jiffies.h>

static int count;
static struct timer_list my_timer;

static void my_timer_callback(struct timer_list *timer)
{
    count++;
    pr_info("-------Timer Count: %d\n", count);

    // 重新启动定时器,在 1 秒后触发
    mod_timer(&my_timer, jiffies + HZ);
}

static int __init my_driver_init(void)
{
    pr_info("Initializing my_driver\n");

    // 初始化定时器
    timer_setup(&my_timer, my_timer_callback, 0);

    // 启动定时器,在 1 秒后触发
    mod_timer(&my_timer, jiffies + HZ);

    return 0;
}

static void __exit my_driver_exit(void)
{
    pr_info("Exiting my_driver\n");

    // 删除定时器
    del_timer(&my_timer);
}

module_init(my_driver_init);
module_exit(my_driver_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A simple driver with a timer");

  我们可以通过dmesg > log来确认效果:

[   37.705643] -------Timer Count: 37
[   38.718969] -------Timer Count: 38
[   39.732309] -------Timer Count: 39
[   40.745674] -------Timer Count: 40