linux内核版本:linux-2.6.30.4
目的:当有按键按下时,在终端输出信息
1 #include <linux/module.h> 2 #include <linux/kernel.h> 3 #include <linux/fs.h> 4 #include <linux/init.h> 5 #include <linux/delay.h> 6 #include <asm/uaccess.h> 7 #include <asm/irq.h> 8 #include <asm/io.h> 9 #include <linux/device.h> 10 11 static struct class *second_drv_class; 12 static struct class_device *second_drv_class_dev; 13 14 static volatile unsigned long *gpfcon; 15 static volatile unsigned long *gpfdat; 16 static int major; 17 18 static int second_drv_open(struct inode *inode, struct file *file) 19 { 20 *gpfcon &= ~((0x3<<0)| (0x3<<2) | (0x3<<4) | (0x3<<8)); 21 return 0; 22 } 23 24 25 static ssize_t second_drv_read(struct file *file, char __user *buf, 26 size_t count, loff_t *ppos) 27 { 28 int ret; 29 unsigned char key_vals[4]; 30 31 if (count != sizeof(key_vals)) 32 return -EINVAL; 33 34 /*k1,k2,k3,k4------gpf1,gpf4,gpf2,gpf0,按下为1*/ 35 ret = *gpfdat; 36 key_vals[0] = (ret & (1<<1)) ? 0 : 1;//k1 37 key_vals[1] = (ret & (1<<4)) ? 0 : 1;//k2 38 key_vals[2] = (ret & (1<<2)) ? 0 : 1;//k3 39 key_vals[3] = (ret & (1<<0)) ? 0 : 1;//k4 40 41 copy_to_user(buf, key_vals, sizeof(key_vals)); 42 43 return sizeof(key_vals); 44 } 45 46 47 static struct file_operations second_fops = { 48 .owner = THIS_MODULE, 49 .open = second_drv_open, 50 .read = second_drv_read, 51 }; 52 53 static int second_init() 54 { 55 int ret; 56 major = register_chrdev(0, "second_drv", &second_fops); 57 second_drv_class = class_create(THIS_MODULE, "second_drv"); 58 device_create(second_drv_class, NULL, MKDEV(major, 0), NULL, "buttons"); 59 60 gpfcon = (volatile unsigned long *)ioremap(0x56000050, 16); 61 gpfdat = gpfcon + 1; 62 63 return 0; 64 } 65 static void second_exit() 66 { 67 unregister_chrdev(major, "second_drv"); 68 device_destroy(second_drv_class, MKDEV(major, 0)); 69 class_destroy(second_drv_class); 70 iounmap(gpfcon); 71 } 72 73 module_init(second_init); 74 module_exit(second_exit); 75 76 MODULE_LICENSE("GPL");
测试例子:
1 #include <sys/types.h> 2 #include <sys/stat.h> 3 #include <fcntl.h> 4 #include <stdio.h> 5 6 /* seconddrvtest 7 */ 8 int main(int argc, char **argv) 9 { 10 int fd; 11 unsigned char key_vals[4]; 12 int cnt = 0; 13 14 fd = open("/dev/buttons", O_RDWR); 15 if (fd < 0) 16 { 17 printf("can't open!\n"); 18 } 19 20 while (1) 21 { 22 read(fd, key_vals, sizeof(key_vals)); 23 if (key_vals[0] || key_vals[1] || key_vals[2] || key_vals[3]) 24 { 25 printf("%04d key pressed: %d %d %d %d\n", cnt++, key_vals[0], key_vals[1], key_vals[2], key_vals[3]); 26 } 27 } 28 29 return 0; 30 }