- 多按键支持
- 按键访问应用程序设计
相关代码
#include <linux/module.h>
#include <linux/init.h>
#include <linux/miscdevice.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#define GPFCON 0x56000050
#define GPFDAT 0x56000054
struct work_struct *work1;
struct timer_list key_timer ;
unsigned int * gpio_data;
unsigned int key_num;
void work1_func(struct work_struct *work)
{
//printk("key down \n");
//启动定时器
//jiffies 是linux是全局变量,表示现在的时间(滴答数)
mod_timer(&key_timer,jiffies + HZ/10);//HZ是1s,这里超时是100ms
}
void key_timer_func(unsigned long delta)
{
unsigned short data ;
data = readw(gpio_data)&0x01 ;
if( data == 0 ){
printk("key4 down \n");
key_num = 4;
}
data = readw(gpio_data)&0x04 ;
if( data == 0 ){
printk("key3 down \n");
key_num = 3;
}
}
irqreturn_t key_int(int irq , void * dev_id)
{
//提交下半部
schedule_work(work1);
return 0;
}
void key_hw_init()
{
unsigned int * gpio_config;
unsigned short data;
gpio_config = ioremap(GPFCON,4);
data = readw(gpio_config);
data &= ~0b110011;
data |= 0b100010;
writew(data,gpio_config);
gpio_data = ioremap(GPFDAT,4);
}
void key_open(struct inode *node, struct file *filp)
{
return 0 ;
}
ssize_t key_read(struct file *filp,char __user *buf,size_t size,loff_t *pos)
{
copy_to_user(buf,key_num,4);
}
struct file_operations key_fops={
.open = key_open,
.read = key_read,
};
struct miscdevice key_miscdev = {
.minor = 200,
.name = "key",
.fops = &key_fops,
};
static int button_init()
{
misc_register(&key_miscdev);
//注册中断处理程序
request_irq(IRQ_EINT0,key_init,IRQF_TRIGGER_FALLING,"key",0); //K4
request_irq(IRQ_EINT2,key_init,IRQF_TRIGGER_FALLING,"key",0); //K3
//按键初始化
key_hw_init();
//创建工作
work1 = kmalloc(sizeof(struct work_struct),GFP_KERNEL);
INIT_WORK(work1,work1_func);
//初始化定时器
init_timer(&key_timer);
//key_timer.expires = 10 ;
key_timer.function = key_timer_func ;
//注册定时器
add_timer(&key_timer);
return 0 ;
}
static void button_exit()
{
misc_deregister(&key_miscdev);
}
module_init(button_init);
module_exit(button_exit);
三、按键访问应用程序
#include <stdio.h>
#include <stdlib.h>
int main()
{
int fd,key_num;
//1.打开设备
fd = open("/dev/2440key",0);
if(fd < 0){
printf("open device fail!\n");
}
//2.读取设备
read(fd,&key_num,4);
printf("key is %d\n",key_num);
//3.关闭设备
close(fd);
}
四、创建设备文件
mknod /dev/2440key c 10 200 // 主设备号10(混杂设备),次设备号200, c是字符设备。