第9章:设备驱动模型(DT & Driver API)
设备树(Devicetree)是一种描述硬件配置的数据结构,用于在Zephyr RTOS中实现硬件抽象层。它允许开发者在不修改内核代码的情况下描述硬件配置。
设备树由节点(nodes)和属性(properties)组成,采用树状结构组织:
/ { // 根节点
compatible = "vendor,board";
soc { // SoC节点
i2c0: i2c@40005000 { // I2C控制器节点
compatible = "nordic,nrf-twim";
reg = <0x40005000 0x1000>;
status = "okay";
sht3xd@44 { // I2C设备节点
compatible = "sensirion,sht3xd";
reg = <0x44>;
label = "SHT3XD";
};
};
};
}
设备树的基本构建块,表示系统中的硬件组件:
i2c0:,用于引用节点描述节点特征的键值对:
以SHT3x温湿度传感器为例的设备树配置:
&i2c0 {
sht3xd@44 {
compatible = "sensirion,sht3xd";
reg = <0x44>;
label = "SHT3XD";
};
};
在prj.conf中启用相关驱动:
CONFIG_I2C=y
CONFIG_SENSOR=y
CONFIG_SHT3XD=y
Zephyr提供了统一的传感器API来访问传感器数据:
#includeconst struct device *sht3xd = DEVICE_DT_GET(DT_NODELABEL(sht3xd)); if (!device_is_ready(sht3xd)) { printk("Sensor device not ready\n"); return; } struct sensor_value temp, humidity; sensor_sample_fetch(sht3xd); sensor_channel_get(sht3xd, SENSOR_CHAN_AMBIENT_TEMP, &temp); sensor_channel_get(sht3xd, SENSOR_CHAN_HUMIDITY, &humidity); printk("温度: %d.%06d °C\n", temp.val1, temp.val2); printk("湿度: %d.%06d %%\n", humidity.val1, humidity.val2);
device_is_ready()检查设备状态/sys/kernel/debug/devices调试信息build/zephyr/zephyr.dts)
客服小姐姐(优先添加)
讲师微信(备用)