当前位置: 首页 > news >正文

正点原子RV1126驱动开发笔记 02

正点原子RV1126驱动开发笔记 02

动态分配设备号

若没有申请设备号,由linux内核动态分配可以使用的设备号

//要返回的申请到的起始设备号,起始次设备号,申请的连续次设备号个数,设备名
int alloc_chrdev_region(dev_t *dev, unsigned baseminor, unsigned count, const char *name) 

若已有设备号,可通过下面的函数来静态申请

//要申请的起始设备号,申请个数,设备名
int regester_chrdev_region(dev_t dev,unsigned count,const char* name)
注:regester_chrdev_region 只可以申请设备号,regester_chrdev 是一键式注册:
自动申请设备号 + 内部创建cdev结构 + 关联fops

注销

void unregister_chrdev_region(dev_t from, unsigned count)

注册与卸载

定义好cdev变量

struct cdev test_cdev;

初始化结构体

void cdev_init(struct cdev *cdev, const struct file_operations *fops);

添加字符设备

int cdev_add(struct cdev *p, dev_t dev, unsigned count)

卸载驱动设备

void cdev_del(struct cdev *p)

自动加载设备节点

自动创建设备节点的工作是在驱动程序的入口函数中完成的
首先要创建一个 class 类,class 是个结构体

struct class *class_create (struct module *owner, const char *name)

卸载驱动程序的时候需要删除掉类,类删除函数为 class_destroy,函数原型如下:

void class_destroy(struct class *cls);

创建好类以后还不能实现自动创建设备节点,我们还需要在这个类下创建一个设备。使用 device_create 函数在类下面创建设备,device_create 函数原型如下:

struct device *device_create(struct class *class,struct device *parent,dev_t devt,void *drvdata,const char* fmt, ...)

卸载驱动的时候需要删除掉创建的设备,设备删除函数为 device_destroy,函数原型如下:

void device_destroy(struct class *cls, dev_t devt)

在入口函数和出口函数下依次调用上面的函数即可实现自动加载和卸载节点

私有属性

编写驱动 open 函数的时候将设备结构体作为私有数据添加到设备文件中

/* 设备结构体 */
struct test_dev{dev_t devid;                   /* 设备号    */struct cdev cdev;              /* cdev     */struct class *class;           /* 类        */struct device *device;         /* 设备      */int major;                     /* 主设备号  */int minor;                     /* 次设备号  */};
struct test_dev testdev;/* open 函数 */
static int test_open(struct inode *inode, struct file *filp)
{filp->private_data = &testdev; /* 设置私有数据 */return 0;
}