Files
Wang Beihong fcc2d0825d first commit
2026-03-14 14:19:32 +08:00

110 lines
3.7 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# i2c_master_messager
`i2c_master_messager` 用于统一管理工程中的 I2C 传感器。
当前已接入:
- BH1750 光照传感器(使用驱动默认地址)
- AHT30 温湿度传感器(使用驱动默认地址)
设计目标:
- 提供统一的数据结构,方便其他模块读取
- 提供独立采集任务,周期性更新数据
- 为后续新增其他 I2C 传感器预留扩展位置
- 各传感器驱动相互独立,管理层只做调度与数据汇总
- 支持每个传感器独立采样周期(例如光照快采、温湿度慢采)
## 驱动分层
- `k0i05__esp_ahtxx`AHT30 驱动组件(通过组件管理器引入)
- `bh1750`:使用 ESP 组件管理器驱动
- `i2c_master_messager.c`:统一总线管理、任务轮询、线程安全数据缓存
## 对外数据结构
头文件:`include/i2c_master_messager.h`
- `i2c_master_messager_data_t`
- `bh1750.lux`光照强度lx
- `bh1750.valid`:当前数据是否有效
- `bh1750.last_update_ms`:最后一次成功更新时间(毫秒)
- `bh1750.last_error`:最后一次采集错误码
- `aht30.temperature_c`:温度(摄氏度)
- `aht30.humidity_rh`:湿度(%RH
- `aht30.valid`:当前数据是否有效
- `aht30.last_update_ms`:最后一次成功更新时间(毫秒)
- `aht30.last_error`:最后一次采集错误码
后续新增传感器时,建议继续在 `i2c_master_messager_data_t` 中增加对应字段。
## API
- `esp_err_t i2c_master_messager_init(const i2c_master_messager_config_t *config);`
- 初始化 I2C 总线(传感器驱动在任务中懒初始化)
- `esp_err_t i2c_master_messager_start(void);`
- 启动循环采集任务
- `esp_err_t i2c_master_messager_stop(void);`
- 停止采集任务
- `esp_err_t i2c_master_messager_get_data(i2c_master_messager_data_t *out_data);`
- 读取当前缓存数据(线程安全)
- `esp_err_t i2c_master_messager_deinit(void);`
- 释放总线和传感器资源
## menuconfig 配置
路径:`Component config -> I2C Master Messager`
- `启用 BH1750 光照传感器`:开关 BH1750
- `启用 I2C 内部上拉电阻`:控制是否打开芯片内部上拉
- `BH1750 采样周期 (ms)`:光照采样周期
- `启用 AHT30 温湿度传感器`:开关 AHT30
- `AHT30 采样周期 (ms)`:温湿度采样周期
这两个周期相互独立,可按业务需求分别调优。
## 使用示例
```c
#include "esp_check.h"
#include "i2c_master_messager.h"
void app_main(void)
{
i2c_master_messager_config_t cfg = {
.i2c_port = I2C_NUM_0,
.scl_io_num = GPIO_NUM_5,
.sda_io_num = GPIO_NUM_4,
.i2c_enable_internal_pullup = true,
.bh1750_enable = true,
.aht30_enable = true,
.bh1750_read_period_ms = 500,
.aht30_read_period_ms = 2000,
.bh1750_mode = BH1750_CONTINUE_1LX_RES,
};
ESP_ERROR_CHECK(i2c_master_messager_init(&cfg));
ESP_ERROR_CHECK(i2c_master_messager_start());
while (1) {
i2c_master_messager_data_t data;
if (i2c_master_messager_get_data(&data) == ESP_OK && data.bh1750.valid && data.aht30.valid) {
printf("BH1750: %.2f lx, AHT30: %.2f C %.2f %%RH\n",
data.bh1750.lux,
data.aht30.temperature_c,
data.aht30.humidity_rh);
}
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
```
## 扩展建议
新增其他传感器时,建议按以下步骤扩展:
1.`i2c_master_messager_data_t` 中增加该传感器的数据结构
2.`i2c_master_messager_config_t` 中增加该传感器配置项
3. 在任务循环中按需完成驱动初始化与重试
4. 在采集任务中加入周期读取逻辑并更新共享数据
5.`deinit()` 中释放对应资源