嵌入式Linux-IMX6ULL-Linux字符设备驱动开发学习总结

1.首先需要创建加载驱动模块函数主要用到

        module_init(xxx_init); //注册模块加载函数

        module_exit(xxx_exit); //注册模块卸载函数

那么就需要创建一个xxx_init函数、一个xxx_exit函数如下所示

/* 驱动入口函数 */
static int __init xxx_init(void)
{
    /* 入口函数具体内容 */
    return 0;
}

/* 驱动出口函数 */
static void __exit xxx_exit(void)
{
    /* 出口函数具体内容 */
}

/* 将上面两个函数指定为驱动的入口和出口函数 */
module_init(xxx_init);
module_exit(xxx_exit);

其中加载驱动模块可以是用insmod xx.ko modprobe.ko 建议使用modprobe不会存在依赖问题,因为命令可以自动分析依赖,自动加载。而卸载模块可以是rmmod xx.ko modprobe -r xx.ko这里建议使用rmmod因为后一个有依赖卸载,本来只要卸载一个驱动,结果把依赖关系的驱动都卸载了就得不偿失了。

2.创建注册和注销函数

        static inline int register_chrdev(unsigned int major, const char *name,
const struct file_operations *fops)
static inline void unregister_chrdev(unsigned int major, const char *name)
 

static struct file_operations test_fops;                //设备驱动操作函数注册结构体

/* 驱动入口函数 */
static int __init xxx_init(void)
{
    /* 入口函数具体内容 */
    int retvalue = 0;
    /* 注册字符设备驱动 */
    retvalue = register_chrdev(200, "chrtest", &test_fops);
    if(retvalue < 0){
        /* 字符设备注册失败,自行处理 */
    }

    return 0;
}

/* 驱动出口函数 */
static void __exit xxx_exit(void)
{
    /* 出口函数具体内容 */
    /* 注销字符设备驱动 */
    unregister_chrdev(200, "chrtest")
}

/* 将上面两个函数指定为驱动的入口和出口函数 */
module_init(xxx_init);
module_exit(xxx_exit);

        注册号了后可以在 cat /proc/devices  文件中看到对于的文件和设备号

3.实现设备具体的操作函数一般就是open、release、read、write
        open

/* 打开设备 */
static int chrtest_open(struct inode *inode, struct file *filp)
{
    /* 用户实现具体功能 */
    return 0;
}

        release

/* 关闭/释放设备 */
static int chrtest_release(struct inode *inode, struct file *filp)
{
    /* 用户实现具体功能 */
    return 0;
}

        read

/* 从设备读取 */
static ssize_t chrtest_read(struct file *filp, char __user *buf,
size_t cnt, loff_t *offt)
{
    /* 用户实现具体功能 */
    return 0;
}

        write

/* 向设备写数据 */
static ssize_t chrtest_write(struct file *filp, const char __user *buf, size_t cnt, loff_t *offt)
{
    /* 用户实现具体功能 */
    return 0;
}

        最后添加到注册结构体中注册

static struct file_operations test_fops = {
    .owner = THIS_MODULE,
    .open = chrtest_open,
    .read = chrtest_read,
    .write = chrtest_write,
    .release = chrtest_release,
};

4.最后添加license和作者信息,license必须要加的不然会编译报错,作者信息自由选择可加可不加

MODULE_LICENSE() //添加模块 LICENSE 信息
MODULE_AUTHOR() //添加模块作者信息

Linux 中每个设备都有一个设备号,设备号由主设备号和次设备号两部分组成,主设备号表示某一个具体的驱动,次设备号表示使用这个驱动的各个设备。主设备号0~4095

Linux推荐用动态分配设备号,这样方便管理。

以上就是字符设备驱动的开发模板了。
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值