You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Device Tree中使用元组并从驱动读取对应数据?

方案可行性确认

这种在Device Tree中定义「字符串+数值」元组的方案完全可行,符合Device Tree的属性定义规范——你可以将多个由字符串和32位整数组成的复合单元(元组)作为属性值,用逗号分隔每个单元。

驱动读取数据的实现方法

Linux内核提供了专门的Device Tree操作API来解析这类复合属性,以下是具体步骤和代码示例:

核心API说明

解析这类元组主要用到以下内核API:

  • of_property_count_strings():统计属性中包含的字符串数量,以此确定元组的总个数
  • of_property_read_string_index():读取指定索引位置的字符串
  • of_property_read_u32_index():读取指定索引位置的32位数值

代码示例

假设你已经获取到目标设备的节点指针struct device_node *np,属性名为"property",示例代码如下:

#include <linux/of.h>
#include <linux/printk.h>

int parse_my_tuple_property(struct device_node *np)
{
    int tuple_count;
    int i;
    const char *str;
    u32 val;

    // 统计元组数量:每个元组对应一个字符串
    tuple_count = of_property_count_strings(np, "property");
    if (tuple_count < 0) {
        pr_err("Failed to count tuples in property: %d\n", tuple_count);
        return tuple_count;
    }

    for (i = 0; i < tuple_count; i++) {
        // 读取第i个元组的字符串
        if (of_property_read_string_index(np, "property", i, &str)) {
            pr_err("Failed to read string at index %d\n", i);
            continue;
        }
        // 读取第i个元组的对应数值
        if (of_property_read_u32_index(np, "property", i, &val)) {
            pr_err("Failed to read u32 value at index %d\n", i);
            continue;
        }
        pr_info("Tuple %d: string = %s, value = 0x%x\n", i, str, val);
    }

    return 0;
}

注意事项

  • Device Tree中的字符串默认以NULL终止,定义元组时无需手动添加\0,编译器会自动处理
  • 如果需要使用64位数值,可替换为of_property_read_u64_index() API
  • 确保驱动中已正确获取设备节点指针,通常可通过platform_device->dev.of_node或device_get_of_node(&dev)获取

内容的提问来源于stack exchange,提问作者Anaadi Mishra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 06:20:21