单片机可以直接访问寄存器;
Linux需要使用虚拟地址(ioremap)。
//驱动程序
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <asm/uaccess.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <asm/arch/regs-gpio.h>
#include <asm/hardware.h>
static struct class *seconddrv_class;
static struct class_device *seconddrv_class_dev;
volatile unsigned long *gpfcon = NULL;
volatile unsigned long *gpfdat = NULL;
volatile unsigned long *gpgcon = NULL;
volatile unsigned long *gpgdat = NULL;
static int second_drv_open(struct inode *inode,struct file *file)
{
*gpfcon &= ~((0x3) | ((0x3)<<4) | (0x3<<(4*2)) | (0x3 <<(5*2)) | (0x3 <<(6*2)));//清零
*gpfcon |= ((0x1<<(4*2)) | (0x1 <<(5*2)) | (0x1 <<(6*2)));
*gpgcon &= ~((0x3<< 6) | (0x3 << 22)) ;//清零
return 0;
}
static ssize_t second_drv_read (struct file *file, char __user *buf, size_t size, loff_t *ppos)
{
unsigned char key_vals[4];
int regval;
if(size != (sizeof(key_vals)))
return -EINVAL;
/*取按键值*/
regval = *gpfdat;
key_vals[0] = (regval & 0x1) ? 1 : 0;
key_vals[1] = (regval & 0x4) ? 1 : 0;
regval = *gpgdat;
key_vals[2] = (regval & 0x8) ? 1 : 0;
key_vals[3] = (regval & 0x1 << 11) ? 1 : 0;
/*传到应用层*/
copy_to_user(buf,key_vals,sizeof(key_vals));
return sizeof(key_vals);
}
static struct file_operations second_drv_fops = {
.owner = THIS_MODULE,
.open = second_drv_open,
.read = second_drv_read,
};
int major;
static int second_drv_init(void)
{
major = register_chrdev(0,"second_drv", &second_drv_fops);
seconddrv_class = class_create(THIS_MODULE, "seconddrv_class");//先创建一个类
seconddrv_class_dev = class_device_create(seconddrv_class, NULL, MKDEV(major, 0), NULL, "wkzybuttons"); /*会创建/dev/wkzy */
gpfcon = (volatile unsigned long *)ioremap(0x56000050,16);//(0x56000050~0x5600005F映射到虚拟内存)
gpfdat = gpfcon + 1;
gpgcon = (volatile unsigned long *)ioremap(0x56000060,16);
gpgdat = gpgcon + 1;
return 0;
}
static int second_drv_exit(void)
{
unregister_chrdev(major,"second_drv");
class_device_unregister(seconddrv_class_dev);//删除设备
class_destroy(seconddrv_class);//删除该类
iounmap(gpfcon);
iounmap(gpfdat);
iounmap(gpgcon);
iounmap(gpgdat);
return 0;
}
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>
/* seconddrvtest
* argv[0]
*/
int main(int argc,char **argv)
{
int fd;
int cnt = 0;
unsigned char key_vals[4];
fd = open("/dev/wkzybuttons",O_RDWR);
if(fd < 0)
{
printf("cant 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 buttons pressd: %d %d %d %d\n",\
cnt++,key_vals[0],key_vals[1],key_vals[2],key_vals[3]);
}
}
return 0;
}
Makefile:
KERN_DIR = /work/system/linux-2.6.22.6
all:
make -C $(KERN_DIR) M=`pwd` modules
clean:
make -C $(KERN_DIR) M=`pwd` modules clean
rm -rf modules.order
obj-m += second_drv.o
make
insmod加载驱动程序
lsmod查看是否加载成功
cat proc/device 看驱动注册的主设备号