添加 MQ-2 传感器支持,初始化 ADC 通道并读取气体浓度

This commit is contained in:
Wang Beihong
2026-04-21 01:17:30 +08:00
parent 85cde3687f
commit f0d8b7fe6e
5 changed files with 125 additions and 2 deletions

View File

@@ -19,6 +19,7 @@
#include "esp_efuse_table.h"
#include "bh1750_use.h"
#include "aht30.h"
#include "MQ-2.h"
#define TAG "MAIN"
@@ -28,6 +29,7 @@ typedef struct
float lux;
float temp;
float humidity;
float gas_percent;
} env_data_t;
static env_data_t s_env_data;
@@ -109,12 +111,15 @@ extern "C" void app_main(void)
aht30_handle_t aht30_dev = NULL;
ESP_ERROR_CHECK(aht30_create(i2c_bus, AHT30_I2C_ADDRESS, &aht30_dev));
// MQ-2 使用 ADC(GPIO8)
ESP_ERROR_CHECK(mq2_init());
// 6. 创建传感器读取任务
xTaskCreate([](void *arg)
{
aht30_handle_t aht30 = (aht30_handle_t)arg;
for (;;) {
float lux = 0.0f, temp = 0.0f, hum = 0.0f;
float lux = 0.0f, temp = 0.0f, hum = 0.0f, gas_percent = 0.0f;
// 读取 BH1750
if (bh1750_user_read(&lux) == ESP_OK) {
set_var_light_val(lux);
@@ -124,6 +129,17 @@ extern "C" void app_main(void)
set_var_temp(temp);
set_var_humity_val(hum);
}
// 读取 MQ-2更新空气质量变量
if (mq2_read_percent(&gas_percent) == ESP_OK) {
set_var_air_quity(gas_percent);
if (s_env_data_lock) {
xSemaphoreTake(s_env_data_lock, portMAX_DELAY);
s_env_data.gas_percent = gas_percent;
xSemaphoreGive(s_env_data_lock);
}
}
// 数据存入共享结构体