78 lines
2.3 KiB
Markdown
78 lines
2.3 KiB
Markdown
# i2c_master_messager
|
||
|
||
`i2c_master_messager` 用于统一管理工程中的 I2C 传感器。
|
||
当前已接入:
|
||
|
||
- BH1750 光照传感器(默认地址 `0x23`)
|
||
|
||
设计目标:
|
||
|
||
- 提供统一的数据结构,方便其他模块读取
|
||
- 提供独立采集任务,周期性更新数据
|
||
- 为后续新增其他 I2C 传感器预留扩展位置
|
||
|
||
## 对外数据结构
|
||
|
||
头文件:`include/i2c_master_messager.h`
|
||
|
||
- `i2c_master_messager_data_t`
|
||
- `bh1750.lux`:光照强度(lx)
|
||
- `bh1750.valid`:当前数据是否有效
|
||
- `bh1750.last_update_ms`:最后一次成功更新时间(毫秒)
|
||
- `bh1750.last_error`:最后一次采集错误码
|
||
|
||
后续新增传感器时,建议继续在 `i2c_master_messager_data_t` 中增加对应字段。
|
||
|
||
## API
|
||
|
||
- `esp_err_t i2c_master_messager_init(const i2c_master_messager_config_t *config);`
|
||
- 初始化 I2C 总线和 BH1750
|
||
- `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);`
|
||
- 释放总线和传感器资源
|
||
|
||
## 使用示例
|
||
|
||
```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,
|
||
.read_period_ms = 1000,
|
||
.bh1750_addr = 0x23,
|
||
.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) {
|
||
printf("BH1750: %.2f lx\n", data.bh1750.lux);
|
||
}
|
||
vTaskDelay(pdMS_TO_TICKS(1000));
|
||
}
|
||
}
|
||
```
|
||
|
||
## 扩展建议
|
||
|
||
新增其他传感器时,建议按以下步骤扩展:
|
||
|
||
1. 在 `i2c_master_messager_data_t` 中增加该传感器的数据结构
|
||
2. 在 `i2c_master_messager_config_t` 中增加该传感器配置项
|
||
3. 在 `i2c_master_messager_init()` 中完成驱动初始化
|
||
4. 在采集任务中加入周期读取逻辑并更新共享数据
|
||
5. 在 `deinit()` 中释放对应资源
|