本文最后更新于329 天前,其中的信息可能已经过时,如有错误请发送邮件到273925452@qq.com

所谓定时器,就是闹钟,时间到后你就要做某些事。有 2 个要素:时间、做事,换成程序员的话就是:超时时间、函数。
内核函数
在 内 核 中 使 用 定 时 器 很 简 单 , 涉 及 这 些 函 数 ( 参 考 内 核 源 码 include\linux\timer.h):
- setup_timer(timer, fn, data):
- 设置定时器,主要是初始化 timer_list 结构体,设置其中的函数、参数。
- void add_timer(struct timer_list *timer):
- 向内核添加定时器。timer->expires 表示超时时间。
- 当 超 时 时 间 到 达 , 内 核 就 会 调 用 这 个 函 数 :timer->function(timer->data)。
- int mod_timer(struct timer_list *timer, unsigned long expires):
- 修改定时器的超时时间,
- 它等同于:del_timer(timer); timer->expires = expires; add_timer(timer);
- 但是更加高效
- int del_timer(struct timer_list *timer):
- 删除定时器。
时间单位
编译内核时,可以在内核源码根目录下用“ls -a”看到一个隐藏文件,它就是内核配置文件。打开后可以看到如下这项:
CONFIG_HZ=100
这表示内核每秒中会发生 100 次系统滴答中断(tick),这就像人类的心跳一样,这是 Linux 系统的心跳。每发生一次 tick 中断,全局变量 jiffies 就会累加 1。
CONFIG_HZ=100 表示每个滴答是 10ms。
定时器的时间就是基于 jiffies 的,我们修改超时时间时,一般使用这 2 种
方法:
1.在 add_timer 之前,直接修改:
timer.expires = jiffies + xxx; // xxx 表示多少个滴答后超时,也就是 xxx*10ms
timer.expires = jiffies + 2*HZ; // HZ 等于 CONFIG_HZ,2*HZ 就相当于 2 秒
2.在 add_timer 之后,使用 mod_timer 修改:
mod_timer(&timer, jiffies + xxx); // xxx 表示多少个滴答后超时,也就是 xxx*10ms
mod_timer(&timer, jiffies + 2*HZ); // HZ 等于 CONFIG_HZ,2*HZ 就相当于 2 秒
使用定时器处理按键抖动
在实际的按键操作中,可能会有机械抖动:
按下或松开一个按键,它的 GPIO 电平会反复变化,最后才稳定。一般是几十毫秒才会稳定。如果不处理抖动的话,用户只操作一次按键,中断程序可能会上报多个数据。怎么处理?
◼ 在按键中断程序中,可以循环判断几十亳秒,发现电平稳定之后再上报
◼ 使用定时器
显然第 1 种方法太耗时,违背“中断要尽快处理”的原则,你的系统会很卡。怎么使用定时器?看下图:
核心在于:在 GPIO 中断中并不立刻记录按键值,而是修改定时器超时时间,10ms 后再处理。
◼ 如果 10ms 内又发生了 GPIO 中断,那就认为是抖动,这时再次修改超时时间为 10ms。
◼ 只有 10ms 之内再无 GPIO 中断发生,那么定时器的函数才会被调用。在定时器函数中记录按键值。
程序
key_timer_drv.c
#include <linux/module.h>
#include <linux/poll.h>
#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/miscdevice.h>
#include <linux/kernel.h>
#include <linux/major.h>
#include <linux/mutex.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/stat.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/tty.h>
#include <linux/kmod.h>
#include <linux/gfp.h>
#include <linux/gpio/consumer.h>
#include <linux/platform_device.h>
#include <linux/of_gpio.h>
#include <linux/of_irq.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/slab.h>
#include <linux/fcntl.h>
#include <linux/timer.h>
struct gpio_key{
int gpio;
struct gpio_desc *gpiod; // gpio描述符
int flag;
int irq;
struct timer_list key_timer; //定时器
};
static struct gpio_key *gpio_keys_100ask;
/* 主设备号 */
static int major = 0;
static struct class *gpio_key_class;
/* 环形缓冲区 */
#define BUF_LEN 128
static int g_keys[BUF_LEN];
static int r, w;
struct fasync_struct *key_fasync; //异步通知
#define NEXT_POS(x) ((x+1) % BUF_LEN)
/* 判断缓冲区是否为空 */
static int is_key_buf_empty(void)
{
return r == w;
}
/* 判断缓冲区是否满了 */
static int is_key_buf_full(void)
{
return NEXT_POS(w) == r;
}
/* 缓冲区写数据 */
static void put_key(int key)
{
if(!is_key_buf_full())
{
g_keys[w] = key;
w = NEXT_POS(w);
}
}
/* 缓冲区读数据 */
static int get_key(void)
{
int key;
if(!is_key_buf_empty())
{
key = g_keys[r];
r = NEXT_POS(r);
}
return key;
}
/* 定义静态的等待队列头变量 用于在Linux内核中处理GPIO按键的中断事件。该等待队列头可以被其他函数用于等待GPIO按键事件的发生,当按键事件发生时,等待队列中的任务将被唤醒。*/
static DECLARE_WAIT_QUEUE_HEAD(gpio_key_wait);
/**
* key_timer_expire - GPIO键定时器到期时的处理函数
* @data: 定时器回调函数的参数,此处为结构体指针struct gpio_key *。
*
* 该函数在GPIO键的定时器到期时被调用。它通过读取GPIO的值来判断键的状态,
* 并根据键的状态发送键事件到内核的输入子系统。
*/
static void key_timer_expire(unsigned long data)
{
/* 将定时器回调函数的参数转换为gpio_key结构体指针 */
/* data ==> gpio */
struct gpio_key *gpio_key = data;
int val; /* 用于存储GPIO的当前值 */
int key; /* 用于构建键事件的键值 */
/* 读取GPIO的值 */
val = gpiod_get_value(gpio_key->gpiod);
printk("key_timer_expire key %d %d\n", gpio_key->gpio, val);
/* 构建键值,高8位为GPIO号,低8位为GPIO的值 */
key = (gpio_key->gpio << 8) | val;
put_key(key);
/* 唤醒可能在等待键事件的进程 */
wake_up_interruptible(&gpio_key_wait);
/* 如果有异步等待键事件的进程,发送SIGIO信号通知它们 */
kill_fasync(&key_fasync, SIGIO, POLL_IN);
}
/* 实现自己的file_operations */
static ssize_t gpio_key_drv_read(struct file *file, char __user *buf, size_t size, loff_t *offset)
{
int err;
int key;
/* is_key_buf_empty(): 判断缓冲区是否为空
file->f_flags: 文件描述符
O_NONBLOCK: 非阻塞模式
*/
if(is_key_buf_empty() && (file->f_flags & O_NONBLOCK))
return -EAGAIN;
/* 将当前进程添加到gpio_key_wait等待队列中,并进入休眠状态,直到is_key_buf_empty()函数的返回值为false */
wait_event_interruptible(gpio_key_wait, !is_key_buf_empty());
key = get_key();
err = copy_to_user(buf, &key, 4);
return 4;
}
static unsigned int gpio_key_drv_poll(struct file *fp, poll_table *wait)
{
poll_wait(fp, &gpio_key_wait, wait); //添加到等待队列中
printk("poll line: %d\n", __LINE__);
return is_key_buf_empty() ? POLLIN : POLLIN | POLLRDNORM;
}
/* 注册异步通知 **/
static int gpio_key_drv_fasync(int fd, struct file *filp, int on)
{
/* 注册或取消注册文件描述符fd的异步通知 */
if (fasync_helper(fd, filp, on, &key_fasync) >= 0)
return 0;
else
return -EIO;
}
/* 定义自己的file_operations结构体 */
static struct file_operations gpio_key_drv = {
.owner = THIS_MODULE,
.read = gpio_key_drv_read,
.poll = gpio_key_drv_poll,
.fasync = gpio_key_drv_fasync,
};
/**
* gpio_key_isr - GPIO按键中断服务函数
*
* @irq: 中断号
* @dev_id: 设备标识符,这里指向结构体gpio_key
*
* 该函数在GPIO按键中断触发时被调用。它负责打印中断发生的信息,并重新设置一个定时器,
* 用于处理按键的消抖和延迟检测。
*
* 返回值: IRQ_HANDLED 表示中断已成功处理。
*/
static irqreturn_t gpio_key_isr(int irq, void *dev_id)
{
/* 将设备标识符转换为gpio_key结构体指针 */
struct gpio_key *gpio_key = dev_id;
printk("gpio_key_isr key %d irq happened\n", gpio_key->gpio);
/* 重新设置定时器,延迟HZ/5秒(HZ=100Hz)后触发,用于处理按键的消抖 */
mod_timer(&gpio_key->key_timer, jiffies + HZ / 5);
return IRQ_HANDLED;
}
/*
1.从platform_device中获GPI信息
2.gpio->irq
3.request_irq
*/
static int gpio_key_probe(struct platform_device * pdev)
{
int err;
struct device_node *node = pdev->dev.of_node; // 获取设备树节点
int count;
int i;
enum of_gpio_flags flag; // GPIO标志位
count = of_gpio_count(node); // 获取GPIO个数
if (!count)
{
printk("%s %s line %d, there isn't any gpio available\n", __FILE__, __FUNCTION__, __LINE__);
return -1;
}
gpio_keys_100ask = kzalloc(sizeof(struct gpio_key) * count, GFP_KERNEL); // 申请内存
for (i = 0; i < count; i++)
{
gpio_keys_100ask[i].gpio = of_get_gpio_flags(node, i, &flag); // 获取GPIO
if (gpio_keys_100ask[i].gpio < 0)
{
printk("%s %s line %d, of_get_gpio_flags fail\n", __FILE__, __FUNCTION__, __LINE__);
return -1;
}
gpio_keys_100ask[i].gpiod = gpio_to_desc(gpio_keys_100ask[i].gpio); // 将gpio转换为描述符
gpio_keys_100ask[i].flag = flag & OF_GPIO_ACTIVE_LOW; // 获取GPIO标志位
gpio_keys_100ask[i].irq = gpio_to_irq(gpio_keys_100ask[i].gpio); // 将GPIO转换为中断号
/* 定时器初始化*/
setup_timer(&gpio_keys_100ask[i].key_timer, key_timer_expire, &gpio_keys_100ask[i]);
gpio_keys_100ask[i].key_timer.expires = ~0; // 超时时间
add_timer(&gpio_keys_100ask[i].key_timer); // 添加定时器
}
/* 注册中断处理程序 */
for (i = 0; i < count; i++)
{
err = request_irq(gpio_keys_100ask[i].irq, gpio_key_isr, IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, "100ask_gpio_key", &gpio_keys_100ask[i]);
}
/* 注册file_operations */
major = register_chrdev(0, "100ask_gpio_key", &gpio_key_drv); /* /dev/gpio_key */
gpio_key_class = class_create(THIS_MODULE, "100ask_gpio_key_class");
if (IS_ERR(gpio_key_class))
{
printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);
unregister_chrdev(major, "100ask_gpio_key");
return PTR_ERR(gpio_key_class);
}
device_create(gpio_key_class, NULL, MKDEV(major, 0), NULL, "100ask_gpio_key"); /* /dev/100ask_gpio_key */
return 0;
}
static int gpio_key_remove(struct platform_device *pdev)
{
struct device_node *node = pdev->dev.of_node;
int count;
int i;
device_destroy(gpio_key_class, MKDEV(major, 0));
class_destroy(gpio_key_class);
unregister_chrdev(major, "100ask_gpio_key");
count = of_gpio_count(node);
for (i = 0; i < count; i++)
{
free_irq(gpio_keys_100ask[i].irq, &gpio_keys_100ask[i]); // 释放中断
del_timer(&gpio_keys_100ask[i].key_timer); // 删除定时器
}
kfree(gpio_keys_100ask); // 释放内存
return 0;
}
/* 设备树匹配表*/
static const struct of_device_id ask100_keys[] = {
{.compatible = "100ask,gpio_key"},
{},
};
/* 定义自己的platform_driver结构体*/
static struct platform_driver gpio_keys_driver = {
.probe = gpio_key_probe,
.remove = gpio_key_remove,
.driver = {
.name = "100ask_gpio_key",
.of_match_table = ask100_keys,
},
};
/* 2. 在入口函数注册platform_driver */
static int __init gpio_key_init(void)
{
int err;
printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);
err = platform_driver_register(&gpio_keys_driver);
return err;
}
/* 3. 有入口函数就应该有出口函数:卸载驱动程序时,就会去调用这个出口函数
* 卸载platform_driver
*/
static void __exit gpio_key_exit(void)
{
printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);
platform_driver_unregister(&gpio_keys_driver);
}
/* 7. 其他完善:提供设备信息,自动创建设备节点 */
module_init(gpio_key_init);
module_exit(gpio_key_exit);
MODULE_LICENSE("GPL");
key_timer_test.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <poll.h>
#include <signal.h>
static int fd;
/*
* ./button_test /dev/100ask_button0
*
*/
int main(int argc, char **argv)
{
int val;
struct pollfd fds[1];
int timeout_ms = 5000;
int ret;
int flags;
int i;
/* 1. 判断参数 */
if (argc != 2)
{
printf("Usage: %s <dev>\n", argv[0]);
return -1;
}
/* 2. 打开文件 */
fd = open(argv[1], O_RDWR | O_NONBLOCK);
if (fd == -1)
{
printf("can not open file %s\n", argv[1]);
return -1;
}
for (i = 0; i < 10; i++)
{
if (read(fd, &val, 4) == 4)
printf("get button: 0x%x\n", val);
else
printf("get button: -1\n");
}
flags = fcntl(fd, F_GETFL);
fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
while (1)
{
if (read(fd, &val, 4) == 4)
printf("get button: 0x%x\n", val);
else
printf("while get button: -1\n");
}
close(fd);
return 0;
}
Makefile
# 1. 使用不同的开发板内核时, 一定要修改KERN_DIR
# 2. KERN_DIR中的内核要事先配置、编译, 为了能编译内核, 要先设置下列环境变量:
# 2.1 ARCH, 比如: export ARCH=arm64
# 2.2 CROSS_COMPILE, 比如: export CROSS_COMPILE=aarch64-linux-gnu-
# 2.3 PATH, 比如: export PATH=$PATH:/home/book/100ask_roc-rk3399-pc/ToolChain-6.3.1/gcc-linaro-6.3.1-2017.05-x86_64_aarch64-linux-gnu/bin
# 注意: 不同的开发板不同的编译器上述3个环境变量不一定相同,
# 请参考各开发板的高级用户使用手册
KERN_DIR = /home/book/100ask_imx6ull-sdk/Linux-4.9.88# 板子所用内核源码的目录
all:
make -C $(KERN_DIR) M=`pwd` modules
$(CROSS_COMPILE)gcc -o button_test button_test.c
clean:
make -C $(KERN_DIR) M=`pwd` modules clean
rm -rf modules.order button_test
# 参考内核源码drivers/char/ipmi/Makefile
# 要想把a.c, b.c编译成ab.ko, 可以这样指定:
# ab-y := a.o b.o
# obj-m += ab.o
obj-m += gpio_key_drv.o
评论