上一篇连接地址:http://blog.csdn.net/qq_21792169/article/details/48414687
驱动程序:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/device.h>
//#include <linux/devfs_fs_kernel.h>
#include <linux/miscdevice.h>
#include <linux/delay.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <mach/regs-gpio.h>
#include <mach/hardware.h>
#include <linux/device.h>
#include <linux/gpio.h>
//volatile unsigned long *GPFCON=NULL;
//volatile unsigned long *GPFDAT=NULL;
#define DEVICE_NAME "buttons"
static struct class *buttons;
static int second_drv_open(struct inode *inode, struct file *file)
{
/* 配置GPF0,2,3,4为输入引脚 */
//*GPFCON = 0x3FFC0C;// GPF0,GPF2,GPF3,GPF4设置为输入
unsigned long temp;
temp=__raw_readl(S3C2410_GPFCON);
temp=0x3FFC0C;
__raw_writel(temp,S3C2410_GPFCON);
return 0;
}
ssize_t second_drv_read(struct file *file, char __user *buf, size_t size, loff_t *ppos)
{
/* 返回4个引脚的电平 */
unsigned char key_vals[4];
int regval;
if (size != sizeof(key_vals))
return -EINVAL;
/* 读GPF0,2 */
regval = __raw_readl(S3C2410_GPFDAT);
key_vals[0] = (regval & (1<<0)) ? 1 : 0;
key_vals[1] = (regval & (1<<2)) ? 1 : 0;
key_vals[2] = (regval & (1<<3)) ? 1 : 0;
key_vals[3] = (regval & (1<<4)) ? 1 : 0;
copy_to_user(buf, key_vals, sizeof(key_vals));
return sizeof(key_vals);//返回读到的数据总数
}
static struct file_operations sencod_drv_fops = {
.owner = THIS_MODULE, /* 这是一个宏,推向编译模块时自动创建的__this_module变量 */
.open = second_drv_open,
.read = second_drv_read,
};
int major;
static int second_drv_init(void)
{
major = register_chrdev(0, "second_drv", &sencod_drv_fops);
buttons = class_create(THIS_MODULE, DEVICE_NAME);
device_create(buttons, NULL, MKDEV(major, 0), NULL, "buttons");
// GPFCON = (volatile unsigned long *)ioremap(0x56000050, 16);
//GPFDAT = GPFCON + 1;
return 0;
}
static void second_drv_exit(void)
{
unregister_chrdev(major, "second_drv");
device_destroy(buttons,MKDEV(major, 0));
class_destroy(buttons);
//iounmap(GPFCON);
}
module_init(second_drv_init);
module_exit(second_drv_exit);
MODULE_LICENSE("GPL");
测试程序:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main(int argc, char **argv)
{
int fd;
unsigned char key_vals[4];
int cnt = 0;
fd = open("/dev/buttons", O_RDWR);
if (fd < 0)
{
printf("can't open!\n");
}
while (1)
{
read(fd, key_vals, sizeof(key_vals));
if (!key_vals[0] || !key_vals[1] || !key_vals[2] || !key_vals[3])
{
printf("%04d key pressed: %d %d %d %d\n", cnt++, key_vals[0], key_vals[1], key_vals[2], key_vals[3]);
}
}
return 0;
}
Makefile其他的部分是不变的,只需要修改文件名字就可以了。
obj-m :=test.o
KERNELDIR ?= /home/work/Linux/linux-2.6.28.7
PWD := $(shell pwd)
default:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
clean:
rm -f *o *.mod.o *mod.c *.symvers *.order