新家装修好厨房有一个自带的燃气报警器(接口24v电压),然而并没有什么用,和物业应该没有通信联系。想了想还是改造一下接入ha配合小米机械手实现燃气自动关阀。
硬件:esp32、mq4传感器、电压转换模块
esphome代码如下:
esphome:
name: mq5sensor
esp32:
board: esp32dev
logger:
level: DEBUG
ota:
platform: esphome
web_server:
port: 80
api:
password: "********"
wifi:
ssid: "******"
password: "*********"
switch:
- platform: restart
name: "ESP Restart Switch"
id: esp_restart_switch
number:
- platform: template
name: "报警阈值"
id: alarm_threshold
initial_value: 150
min_value: 100
max_value: 10000
step: 100
icon: "mdi:alert-circle"
optimistic: true
binary_sensor:
- platform: template
name: "天然气报警 状态"
id: gas_alarm_status
lambda: |-
// Use LPG concentration sensor ID
float ppm = id(LPG_Concentration).state;
float threshold = id(alarm_threshold).state;
return ppm >= threshold;
sensor:
# Raw voltage sensor (ADC reading)
- platform: adc
pin: GPIO33
id: mq5_raw_voltage
name: "MQ5_Raw_Voltage"
update_interval: 1s
unit_of_measurement: "V"
attenuation: 12db # Fix deprecated warning
filters:
- lambda: |-
// Convert ADC raw value to voltage
float voltage = (float)x / 0.694; // Assume ADC resolution is 12-bit
return roundf(voltage * 1000) / 1000; // Round to 3 decimal places
# LPG concentration calculation template sensor
- platform: template
name: "LPG_Concentration"
id: LPG_Concentration # Add ID definition
lambda: |-
static float last_ppm = 0; // Cache the last valid PPM value
float voltage = id(mq5_raw_voltage).state;
if (voltage == 0 || voltage >= 5.0) {
return last_ppm; // If voltage is invalid, return the last PPM value
}
float ppm = 39.2332667161086 * exp(1.46671939878595 * voltage);
last_ppm = roundf(ppm * 10) / 10; // Round to 1 decimal place and update cache
return last_ppm;
unit_of_measurement: "ppm"
accuracy_decimals: 1
update_interval: 1s # Increase update frequency to 200ms
text_sensor:
- platform: template
name: "ESP 设备 IP 地址"
lambda: |-
return std::string(WiFi.localIP().toString().c_str());
注意:1.最好不要用打火机测试燃气数值,容易损坏传感器。
2.电压和浓度ppm值我折腾了好几天差了很多资料很多视频都没有好的解决办法。现在的计算函数是官方文档中电压ppm值函数图取点拟合函数后的计算公式。
3.我的电路使用了分压电路,两个10千欧并联后与一个2.2千欧电阻串联。分压比为0.694。具体原理请自行了解。
|