Linux字符设备驱动-树莓派IO口驱动框架

驱动俩大利器 :
1.电路图:作用:通过电路图找到寄存器
2.芯片手册

芯片手册第六章:
GPFSEL0 :寄存器配置:(input/output) GPIO Function Select 0 功能选择: 输出/输入 (GPIO Function Select Registers )32位
14-12 001 = GPIO Pin4 is an output
000 = GPIO Pin4 is an input

引脚(置1和置0) 1高电平 0低电平
GPSET0 GPIO Pin Output Set 0 输出1
0 = No effect
1 = Set GPIO pin n

GPCLR0 GPIO Pin Output Clear 0 清0
0 = No effect
1 = Set GPIO pin n

volatile 1 .指令不会因编译器的优化而省略 2.且要求每次直接读值

《《《《编程步骤》》》》以Pin4为例

定义:

volatile unsigned int* GPFSEL0;
volatile unsigned int* GPSET0;
volatile unsigned int* GPCLR0;

一丶在init函数里映射函数(物理地址转虚拟地址):
GPFSEL0 寄存器起始地址是:0x3f200000

GPFSEL0 = (volatile unsigned int*)ioremap(0x3f200000,4);
 GPSET0 = (volatile unsigned int*)ioremap(0x3f20001C,4);
 GPCLR0 = (volatile unsigned int*)ioremap(0x3f200028,4);

二丶在open函数里配置 (配置成OUTPUT 为001 )

 *GPFSEL0 &= ~(0x6 << 12);             //配置13 14 位为0
 *GPFSEL0 |= ~(0x1 << 12);              //配置12 位为0

三丶在write函数里配置

使用函数copy_from_user(&buf,user_buf,count); //读取用户输入

*GPSET0 |= 0x1 <<4;   //置1
*GPCLR0 &=0x1 <<4;   //置0

四丶解绑映射:iounmap(GPFSEL0);

Linux内核驱动基础框架

#include <linux/fs.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/uaccess.h>
#include <linux/types.h>
#include <asm/io.h>


static struct class *pin6_class;
static struct device *pin6_class_dev;

static dev_t devno;
static int major =234;
static int minor =0;
static char *module_name="pin6";



volatile unsigned int* GPFSEL0;
volatile unsigned int* GPSET0;
volatile unsigned int* GPCLR0;




static int pin6_open(struct inode *inode,struct file *file)
{
    
    

	printk("pin6_open\n");

	*GPFSEL0 &= ~(0x6 << 18);
	*GPFSEL0 |= (0x1 << 18);		


	return 0;

}


static ssize_t pin6_write(struct file *file,const char __user *buf,size_t count, loff_t *ppos)
{
    
    

	int userCmd;
	printk("pin6_write\n");

	copy_from_user(&userCmd,buf,count);

	if(userCmd == 1)
	{
    
    
		printk("set 1");
		*GPSET0 |= 0x1 << 6;

	}else if(userCmd == 0){
    
    

		printk("set 0");
		*GPCLR0 |= 0x1 << 6; 
	}

	return 0;
}

static struct file_operations pin6_fops = {
    
    

	.owner = THIS_MODULE,
	.open  = pin6_open,
	.write = pin6_write,



};

int __init pin6_drv_init(void)
{
    
    

	int ret;
	devno = MKDEV(major,minor);
	ret   = register_chrdev(major, module_name,&pin6_fops);

	pin6_class=class_create(THIS_MODULE,"mytwodemo");
	pin6_class_dev =device_create(pin6_class,NULL,devno,NULL,module_name);


	GPFSEL0 = (volatile unsigned int*)ioremap(0x3f200000,4);
	GPSET0 = (volatile unsigned int*)ioremap(0x3f20001C,4);
	GPCLR0 = (volatile unsigned int*)ioremap(0x3f200028,4);
	return 0;

}

void __exit pin6_drv_exit(void)
{
    
    
	iounmap(GPFSEL0);
	iounmap(GPSET0);
	iounmap(GPCLR0);
	device_destroy(pin6_class,devno);
	class_destroy(pin6_class);
	unregister_chrdev(major, module_name);

}



module_init(pin6_drv_init);
module_exit(pin6_drv_exit);
MODULE_LICENSE("GPL v2");

猜你喜欢

转载自blog.csdn.net/hhltaishuai/article/details/107463011