[linux驱动开发--读设备树] 基于qemu9.1+linux内核6.11.0
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/platform_device.h>
static int __init my_driver_init(void)
{
struct device_node *bus_node;
struct device_node *motherboard_node;
struct device_node *leds_node;
const char *compatible;
// 查找根节点下的 bus@40000000
bus_node = of_find_node_by_name(NULL, "bus");
if (!bus_node) {
pr_err("bus@40000000 node not found\n");
return -ENODEV;
}
// 在 bus@40000000 下找到 motherboard-bus@40000000
motherboard_node = of_get_child_by_name(bus_node, "motherboard-bus");
if (!motherboard_node) {
pr_err("motherboard-bus@40000000 node not found\n");
of_node_put(bus_node);
return -ENODEV;
}
// 在 motherboard-bus@40000000 下找到 leds 节点
leds_node = of_get_child_by_name(motherboard_node, "leds");
if (!leds_node) {
pr_err("leds node not found\n");
of_node_put(motherboard_node);
of_node_put(bus_node);
return -ENODEV;
}
// 读取 leds 节点的 compatible 属性
if (of_property_read_string(leds_node, "compatible", &compatible) == 0) {
pr_info("LEDs compatible property: %s\n", compatible);
} else {
pr_err("Failed to read compatible property from LEDs node\n");
}
// 释放节点引用
of_node_put(leds_node);
of_node_put(motherboard_node);
of_node_put(bus_node);
return 0;
}
static void __exit my_driver_exit(void)
{
pr_info("Driver exit\n");
}
module_init(my_driver_init);
module_exit(my_driver_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("Device Tree Property Access Example");