[linux驱动开发--读设备树] 基于qemu9.1+linux内核6.11.0
本文档模拟vexpress-a9开发板,作为铁头娃,要学就学最新的版本
环境搭建请看我这篇博客
1. 查找设备树文件位置
arch/arm/boot/dts/arm/vexpress-v2p-ca9.dts
arch/arm/boot/dts/arm/vexpress-v2m.dtsi
- 关于
.dts
和.dtsi
的区别,请看我这篇博客
2. 要读取的节点属性
尝试读取此节点的compatible属性,节点:
根节点
-->bus@40000000
-->motherboard-bus@40000000
-->leds
-->compatible = "gpio-leds";
3. 测试代码
内核的OF函数API文档
#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");
4. Makefile编译
记得把linux内核根目录的路径改成你电脑上的
KERNELDIR := ~/qemu_9.1/linux
CROSS_COMPILE := arm-linux-gnueabihf-
CURRENT_PATH := $(shell pwd)
obj-m := device_tree.o
build: kernel_modules
kernel_modules:
$(MAKE) -C $(KERNELDIR) M=$(CURRENT_PATH) ARCH=arm CROSS_COMPILE=$(CROSS_COMPILE) modules
clean:
$(MAKE) -C $(KERNELDIR) M=$(CURRENT_PATH) ARCH=arm CROSS_COMPILE=$(CROSS_COMPILE) clean
记得把复制路径改成你的根文件系统相应路径
make -j12
cp -rf device_tree.ko your_rootfs_path/lib/modules/6.11.0/