编写一个最简单的设备树节点(.dts),并在驱动中读取它的 compatible 属性
设备树(Device Tree)是一种描述硬件配置的数据结构,广泛应用于嵌入式Linux系统中。它允许内核在不重新编译的情况下支持多种硬件平台。
设备树源文件(.dts)包含一个根节点和多个子节点,每个节点描述一个硬件设备及其属性。
/dts-v1/;
/ {
model = "My Board";
compatible = "my-board";
my_device: my_device@0 {
compatible = "my-device";
reg = <0x10000000 0x1000>;
status = "okay";
};
};
以下是一个最简单的设备树节点示例,定义了一个名为"hello_device"的设备。
/dts-v1/;
/ {
compatible = "my-board", "simple-bus";
#address-cells = <1>;
#size-cells = <1>;
hello_device: hello_device@0 {
compatible = "hello-device";
reg = <0x10000000 0x1000>;
status = "okay";
};
};
在Linux内核驱动中,我们可以通过of_match_table来匹配设备树节点,并读取其属性。
#include
#include
#include
static const struct of_device_id hello_of_match[] = {
{ .compatible = "hello-device", },
{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(of, hello_of_match);
static int hello_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
const char *compatible;
compatible = of_get_property(dev->of_node, "compatible", NULL);
if (compatible)
dev_info(dev, "Compatible: %s\n", compatible);
return 0;
}
static struct platform_driver hello_driver = {
.driver = {
.name = "hello-device",
.of_match_table = hello_of_match,
},
.probe = hello_probe,
};
module_platform_driver(hello_driver);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A simple device tree example");
概念 | 描述 | 示例 |
---|---|---|
compatible | 用于匹配设备和驱动的字符串 | "hello-device" |
reg | 设备的地址和大小 | <0x10000000 0x1000> |
status | 设备状态 | "okay" 或 "disabled" |
of_match_table | 驱动中用于匹配的设备表 | hello_of_match |
确保设备树中的compatible字符串与驱动中的完全一致,包括大小写。
使用of_get_property函数时,要检查返回值是否为NULL。
在QEMU环境中测试时,需要通过-drive参数加载设备树二进制文件。