基于中断的按键驱动以及其测试程序

来源:互联网 发布:志丹县县政府网络平台 编辑:程序博客网 时间:2024/05/03 17:17

驱动程序如下

#include <linux/device.h>

#include <linux/interrupt.h>

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/irq.h>
#include <asm/uaccess.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <mach/gpio.h>
#include<linux/cdev.h>
 
int key_id;
struct cdev cdev;
dev_t devno;
/*等待队列头*/
wait_queue_head_t key_q;
/*中断事件标志,中断服务程序将它置为1,read函数将它置为0*/
unsigned int key_num=0;
#define DRIVER_NAME "my_key_driver"
struct class *my_class;

static irqreturn_t key_func(int irq,void *dev_id)
{
key_id=(int)dev_id;


/*唤醒*/
key_num=1;
wake_up(&key_q);




return 0;
}


static int key_open(struct inode *inode,struct file *file)
{


request_irq(IRQ_EINT(16),key_func,IRQF_TRIGGER_FALLING,"k1",1);
request_irq(IRQ_EINT(17),key_func,IRQF_TRIGGER_FALLING,"k2",2);
request_irq(IRQ_EINT(18),key_func,IRQF_TRIGGER_FALLING,"k3",3);
request_irq(IRQ_EINT(19),key_func,IRQF_TRIGGER_FALLING,"k4",4);
request_irq(IRQ_EINT(24),key_func,IRQF_TRIGGER_FALLING,"k5",5);
request_irq(IRQ_EINT(25),key_func,IRQF_TRIGGER_FALLING,"k6",6);
request_irq(IRQ_EINT(26),key_func,IRQF_TRIGGER_FALLING,"k7",7);
request_irq(IRQ_EINT(27),key_func,IRQF_TRIGGER_FALLING,"k8",8);
return 0;
}


static int key_close(struct inode *inode,struct file *file)
{


free_irq(IRQ_EINT(16),1);
free_irq(IRQ_EINT(17),2);
free_irq(IRQ_EINT(18),3);
free_irq(IRQ_EINT(19),4);
free_irq(IRQ_EINT(24),5);
free_irq(IRQ_EINT(25),6);
free_irq(IRQ_EINT(26),7);
free_irq(IRQ_EINT(27),8);


return 0;
}


ssize_t key_read(struct file *filp, char __user *buf, size_t size,loff_t *pos)
{
/*如果没有按键按下,休眠,让出CPU*/
wait_event(key_q,key_num);
/*如果有按键按下*/
copy_to_user(buf,&key_id,sizeof(key_id)); 
key_num=0;


return 0;
}




static struct file_operations key_fops =
{
.owner = THIS_MODULE,
.open = key_open,
.release = key_close,
.read=key_read,
};




static int __init key_interrupt_init(void)
{
cdev_init(&cdev,&key_fops);
alloc_chrdev_region(&devno, 0 , 1 , "mykey_interrupt");
cdev_add(&cdev, devno, 1);
my_class = class_create(THIS_MODULE, "key_interrupt_class");
if(IS_ERR(my_class))
{
printk("Err: failed in creating class.\n");
return -1;
}
device_create(my_class, NULL, devno,NULL,"key_interrput_driver");
init_waitqueue_head(&key_q);
return 0;
}


static void key_interrupt_exit(void)
{
device_destroy(my_class,devno);
class_destroy(my_class);
cdev_del(&cdev);
unregister_chrdev_region(devno,1);
}


module_init(key_interrupt_init);
module_exit(key_interrupt_exit);
MODULE_LICENSE("GPL");

MODULE_AUTHOR("EIGHT_FIVE");


测试程序如下

#include<stdio.h>
#include<sys/ioctl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>


int main(int argv,char **argc)
{
int fd,buf;
fd=open("/dev/key_interrput_driver",0x666);


while(1)
{


read(fd,&buf,4);
printf("key_val =%d\n",buf);
}
return 0;


}



0 0