drive 这边
static irqreturn_t sun8i_key_irq_handler(int irq, void *dev_id)
{
/* 10ms后启动定时器 */
struct key_list_t *pdev = &pkey;
return IRQ_RETVAL(IRQ_HANDLED);
}
static int sixth_drv_open(struct inode *inode, struct file *file)
{
struct key_list_t *kdev = &pkey;
int ret;
if (file->f_flags & O_NONBLOCK)//O_NONBLOCK非阻塞
{
if (down_trylock(&button_lock))
return -EBUSY;
}
else
{
/* 获取信号量 */
down(&button_lock);
}
kdev->key_irq = gpio_to_irq(GPIOH(9));
if (IS_ERR_VALUE(kdev->key_irq)) {
dprintk("map gpio [%d] to irq failed, errno = %d\n",GPIOH(9),kdev->key_irq);
return -EINVAL;
}
dprintk("map gpio_%d to irq success, irq = %d\n",kdev->pio.gpio,kdev->key_irq);
ret = request_irq(kdev->key_irq,sun8i_key_irq_handler,IRQF_BOTHEDGE,"PH9_EINT", &pins_desc[0]);
if (IS_ERR_VALUE(ret)) {
dprintk("failed to request irq\n");
return ret;
}
return 0;
}
ssize_t sixth_drv_read(struct file *file, char __user *buf, size_t size, loff_t *ppos)
{
if (size != 1)
return -EINVAL;
if (file->f_flags & O_NONBLOCK)
{
if (!ev_press) /* ev_press 中断事件标志, 中断服务程序将它置1,sixth_drv_read将它清0 */
return -EAGAIN;
}
else
{
/* 如果没有按键动作, 休眠 */
wait_event_interruptible(button_waitq, ev_press);
}
/* 如果有按键动作, 返回键值 */
copy_to_user(buf, &key_val, 1);
ev_press = 0;
return 1;
}
static struct file_operations sencod_drv_fops = {
.owner = THIS_MODULE,
.open = sixth_drv_open,
.read = sixth_drv_read,
.release = sixth_drv_close,
.poll = sixth_drv_poll,
.fasync = sixth_drv_fasync,
};
static int __init key_input_init(void)
{
keymajor = register_chrdev(0, "sixth_drv", &sencod_drv_fops);
sixthdrv_class = class_create(THIS_MODULE, "sixth_drv");
sixthdrv_class_dev = device_create(sixthdrv_class, NULL, MKDEV(major, 0), NULL, "buttons");
return 0;
}
app这边
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/input.h>
#include <sys/fcntl.h>
int main(int argc, char *argv[])
{
int fd = -1;
int num;
size_t rb;
int version;
char name[20];
struct input_event ev;
int i=0;
if ((fd = open("/dev/input/event4", O_RDONLY)) < 0) //打开设备
{
perror("open error");
exit(1);
}
while(1)
{
rb = read(fd, &ev, sizeof(struct input_event)); //读取设备
if (rb < (int)sizeof(struct input_event)) //读取错误
{
perror("read error");
exit(1);
}
if (EV_KEY==ev.type) //读取的是否是按键内容
{
if (1 == ev.value) //key1被按下
printf("key is pressed\n");
else //key1被释放
printf("key is released\n");
}
}
close(fd);
return 0;
}