一、以中断方式实现的按键驱动
1.确定主设备号,创建设备节点。
int major;
static int btn_drv_init(void)
{
major = register_chrdev(0, "btn_drv", &btn_drv_fops);
btndrv_class = class_create(THIS_MODULE, "btn_drv");
btndrv_dev = device_create(btndrv_class, NULL, MKDEV(major, 0), NULL, "buttons");
2.初始化一个file_operations结构体。
static struct file_operations btn_drv_fops = {
.owner = THIS_MODULE,
.open = btn_drv_open,
.read = btn_drv_read,
.release = btn_drv_close,
.poll = btn_drv_poll,
.fasync = btn_drv_fasync,
};
3.申请gpio及中断号,注册中断,并设置为输入。
keys_desc[i].irq=gpio_to_irq(keys_desc[i].key_number);
gpio_request(keys_desc[i].key_number, keys_desc[i].name);
gpio_direction_input(keys_desc[i].key_number);
request_irq(keys_desc[i].irq, buttons_irq, IRQF_TRIGGER_RISING, keys_desc[i].name,(void *)&keys_desc[i]);
4.在read函数中,若没有按键按下就休眠。
wait_event_interruptible(button_waitq, ev_press);
按键按下,调用中断程序,确定哪个按键按下,唤醒按键程序。
ev_press = 1;
wake_up_interruptible(&button_waitq);
测试程序:
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <stdio.h>
#include <poll.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
int fd,ret;
void my_signal_fun(int signame)
{
read(fd,&ret,sizeof(ret));
printf("key_value=%#x\r\n",ret);
}
int main(int argc,char **argv)
{
int oflag;
unsigned int val = 0;
fd = open("/dev/buttons",O_RDWR);
if(fd < 0)
{
printf("open buttons error!\n");
return -1;
}
signal(SIGIO,my_signal_fun);
fcntl(fd,F_SETOWN,getpid());
oflag = fcntl(fd,F_GETFL);
fcntl(fd,F_SETFL,oflag|FASYNC);
while(1)
{
sleep(1000);
}
return 0;
}
二、将按键写入input子系统
1.申请gpio及中断号,注册中断,并设置为输入。
同上一的3.
2.初始化一个input_dev结构体,并注册这个input设备。
static struct input_dev *button_dev;
button_dev->name = "juzone";
button_dev->phys = "buttons/input0";
button_dev->id.bustype = BUS_HOST;
button_dev->id.vendor = 0x0001;
button_dev->id.product = 0x0001;
button_dev->id.version = 0x0100;
input_register_device(button_dev);
3.按键按下,调用中断程序,确定哪个按键按下,上报input子系统。
input_report_key(button_dev,pinval,1);
input_report_key(button_dev,pinval,0);
按下按键的效果就是相当于按下了键盘的某个键,通过
set_bit(keys_desc[i].xuhao,button_dev->keybit);
来确定是哪个按键,keys_desc[i].xuhao代表按键的值,在input.h中有定义。