添加Linux 的 i2c设备驱动
1、设备树的添加
一般添加在kernel/arch/arm64/boot/dts/xxx.dts文件中
&hsi2c_1 {                //这里的hsi2c_1的意思是该设备挂载在i2c 1总线上,该值需要由硬件的spec查询的来
    status = "okay";

    testdevices@48{            //这里配置的name需要与驱动文件中配置的相同
        compatible = "testdevices";
        reg = <0x48>;        //这里是设备的i2c地址,同样是由硬件的spec查询得到
        slave-mode;
    };
    
};
这里系统启动时,会遍历设备树注册“testdevices_match”设备
2、设备驱动的添加
驱动一般添加在kernel/driver/相关的目录下,根据自己需求放在其他已有目录下,或者新建目录。重点是要确保新添加的会被编译到
驱动文件的添加:
本例添加在kernel/driver/media/下
testdevices.c
static int testdevices_probe(struct i2c_client *client,
                            const struct i2c_device_id *id)
{

    return 0;
}

static int testdevices_remove(struct i2c_client *client)
{

    return 0;
}

static const struct of_device_id testdevices_match[] = {
    {.compatible = "testdevices",},
    {},
};

MODULE_DEVICE_TABLE(of, testdevices_match);


static struct i2c_driver testdevices_i2c_driver = {
        .driver = {
                .name    = "testdevices",
                .owner    = THIS_MODULE,
                .of_match_table = testdevices_match
        },
        .probe    = testdevices_probe,
        .remove    = testdevices_remove,
};

module_i2c_driver(testdevices_i2c_driver);
MODULE_AUTHOR("testdevices");
MODULE_DESCRIPTION("testdevices I2C Bus Support Module");
MODULE_LICENSE("GPL v2");

系统启动时,通过module_i2c_driver加载驱动,然后通过testdevices_match中配置的name与已注册设备进行匹配,匹配成功后,开始执行testdevices_probe到这里设备驱动就添加成功了。
对设备进行操作函数可以根据自己需要添加到这个文件中
注意需要在编译的Makefile以及Kconfig中添加编译,否则驱动文件不会被编译进内核,这个可以参照同目录下其他驱动修改即可

i2c设备以及驱动的注册匹配工作在kernel/driver/i2c/i2c-core-base.c文件中

驱动添加完成以后,可以在sys/class/i2c/ 目录下找到相关设备节点

Logo

更多推荐