最近移植了linux内核, 制作了文件系统,于是就写了一个简单key驱动检验一下.
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define DEVICE_NAME "mini2440_key"
#define KEY_MAJOR 232
static DECLARE_WAIT_QUEUE_HEAD(key_waitq);
static volatile int ev_press = 0;
static volatile int press_cnt[] = { 0, 0, 0, 0, 0, 0};
struct key_irq_desc {
unsigned int irq;
unsigned long flags;
const char *name;
};
static struct key_irq_desc key_irqs[] = {
{IRQ_EINT8, IRQT_FALLING, "key1"},
{IRQ_EINT11, IRQT_FALLING, "key2" },
{IRQ_EINT13, IRQT_FALLING, "key3"},
{IRQ_EINT14, IRQT_FALLING, "key4"},
{IRQ_EINT15, IRQT_FALLING, "key5"},
{IRQ_EINT19, IRQT_FALLING, "key6"}
};
static irqreturn_t key_interrupt(int irq, void *dev_id)
{
volatile int *press_cnt = (volatile int *)dev_id;
*press_cnt = *press_cnt + 1;
ev_press = 1;
wake_up_interruptible(&key_waitq);
return IRQ_RETVAL(IRQ_HANDLED);
}
static int mini2440_key_open(struct inode *inode, struct file *file)
{
int i;
int err;
for (i = 0; i < sizeof(key_irqs) / sizeof(key_irqs[0]); i++)
{
err = request_irq(key_irqs[i].irq, key_interrupt, key_irqs[i].flags, \
key_irqs[i].name, (void *)&press_cnt[i]);
if (err)
{
break;
}
}
if (err)
{
i--;
for (; i >= 0; i--)
{
free_irq(key_irqs[i].irq, (void *)&press_cnt[i]);
}
}
return 0;
}
static int mini2440_key_release(struct inode *inode, struct file *file)
{
int i;
for (i = 0; i < sizeof(key_irqs) / sizeof(key_irqs[0]); i++)
{
free_irq(key_irqs[i].irq, (void *)&press_cnt[i]);
}
return 0;
}
static int mini2440_key_read(struct file *filp, char __user *buff, size_t count, loff_t *offp)
{
unsigned long err;
wait_event_interruptible(key_waitq, ev_press);
ev_press = 0;
err = copy_to_user(buff, (const void *)press_cnt, min(sizeof(press_cnt), count));
memset((void *)press_cnt, 0, sizeof(press_cnt));
return err ? -EFAULT : 0;
}
static struct file_operations mini2440_key_fops = {
.owner = THIS_MODULE,
.open = mini2440_key_open,
.release = mini2440_key_release,
.read = mini2440_key_read,
};
static int __init mini2440_key_init(void)
{
int ret;
ret = register_chrdev(KEY_MAJOR, DEVICE_NAME, &mini2440_key_fops);
if (ret < 0)
{
printk(KERN_NOTICE"can not register major number\n");
return ret;
}
printk(KERN_INFO" register sucess\n");
return 0;
}
static int __exit mini2440_key_exit(void)
{
unregister_chrdev(KEY_MAJOR, DEVICE_NAME);
return 0;
}
module_init(mini2440_key_init);
module_exit(mini2440_key_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("more&&high");
insmod mini2440_key.ko
mknod /dev/mini2440_key c 232 0
测试程序
./test_key
/home # ./test_key
key 3 has been pressed 1 times!
/home # ./test_key
key 4 has been pressed 1 times!
/home # ./test_key
key 6 has been pressed 1 times!
/home #
阅读(1736) | 评论(0) | 转发(0) |