ESP32 Gas Sensor Application Guide
1. Basic Principles and Selection
Gas sensors operate by detecting electrochemical changes (such as resistance changes) caused by target gases. Common types include:
- MQ Series detects specific gases (such as smoke, liquefied gas) and outputs an analog voltage.
- Digital Sensors directly output I²C digital signals (such as BME680 for multi-parameter monitoring).
Practical Selection Guide:
| Application Scenario | Recommended Sensor | Features |
|---|---|---|
| Fire Alarm | MQ-2 | Low-cost smoke detection |
| Kitchen Safety | MQ-5 | High sensitivity liquefied gas detection |
| Air Quality Monitoring | MQ-135 | Detection of pollutants like benzene and ammonia |
| Indoor Environment Monitoring | BME680 | Temperature, humidity, pressure + gas four-in-one |
2. Wiring and Configuration
Basic Wiring for MQ Series:
MQ Sensor → ESP32
-----------------
VCC → 3.3V or 5V*
GND → GND
AOUT → GPIO34 (Analog Input)
* 5V power supply requires a voltage divider circuit
BME680 Digital Sensor Wiring:
BME680 → ESP32
-----------------
VCC → 3.3V
GND → GND
SCL → GPIO22 (I²C Clock)
SDA → GPIO21 (I²C Data)
3. Simple Code Examples
Smoke Detection System
// Pin definitions
const int SMOKE_PIN = 34;
const int ALARM_LED = 2; // Onboard LED
void setup() {
Serial.begin(115200);
pinMode(SMOKE_PIN, INPUT);
pinMode(ALARM_LED, OUTPUT);
}
void loop() {
int value = analogRead(SMOKE_PIN);
// Convert raw value (0-4095)
Serial.print("Smoke Concentration: ");
Serial.println(value);
// Simple alarm: value > 1500 triggers
if(value > 1500) {
digitalWrite(ALARM_LED, HIGH);
Serial.println("Warning: Smoke detected!");
} else {
digitalWrite(ALARM_LED, LOW);
}
delay(1000); // Check once per second
}
Air Quality Monitoring
#include <Wire.h>
#include "Adafruit_BME680.h"
Adafruit_BME680 bme;
void setup() {
Serial.begin(115200);
// Initialize BME680
if(!bme.begin()) {
Serial.println("Sensor not found");
while(1);
}
// Configure sensor parameters
bme.setTemperatureOversampling(BME680_OS_2X);
bme.setHumidityOversampling(BME680_OS_2X);
bme.setGasHeater(320, 150); // 320°C heating for 150ms
}
void loop() {
// Read data
if(!bme.performReading()) {
Serial.println("Reading failed");
return;
}
// Print results
Serial.print("Temperature: "); Serial.print(bme.temperature); Serial.println("°C");
Serial.print("Humidity: "); Serial.print(bme.humidity); Serial.println("% ");
Serial.print("Pressure: "); Serial.print(bme.pressure/100.0); Serial.println("hPa");
Serial.print("Gas Resistance: "); Serial.print(bme.gas_resistance); Serial.println("Ω");
Serial.println("-----------------");
delay(3000); // Check every 3 seconds
}
4. Data Processing Methods
Concentration Conversion Formula
For the MQ-2 sensor:
RS = (3.3 * 4095 / rawADC) - 1 // Calculate sensor resistance
R0 = Resistance value of the sensor in clean air
ratio = RS / R0
// Approximate calculation of smoke concentration
smoke_ppm = 500 * pow(ratio, -1.8)
Practical Alarm Logic
void checkAirQuality(float gasResistance) {
// Determine air quality based on gas resistance
if(gasResistance > 200000) {
Serial.println("Air Quality: Excellent");
} else if(gasResistance > 100000) {
Serial.println("Air Quality: Good");
} else if(gasResistance > 50000) {
Serial.println("Air Quality: Moderate");
} else {
Serial.println("Air Quality: Poor - Ventilation recommended!");
}
}
5. Application Scenario Implementation
Kitchen Safety System
void monitorKitchen() {
int gasLevel = analogRead(GAS_SENSOR_PIN);
// Multi-level response mechanism
if(gasLevel > 2000) {
// 1. Sound and light alarm
activateAlarm();
// 2. Close gas valve
digitalWrite(VALVE_CONTROL_PIN, LOW);
// 3. Start exhaust fan
digitalWrite(FAN_CONTROL_PIN, HIGH);
}
else if(gasLevel > 1500) {
// Pre-warning level
blinkWarningLED();
}
}
Smart Ventilation Control
void autoVentilation() {
if(needFreshAir()) {
digitalWrite(FAN_PIN, HIGH);
Serial.println("Starting ventilation system");
} else {
digitalWrite(FAN_PIN, LOW);
}
}
bool needFreshAir() {
// Comprehensive assessment of air indicators
float co2 = readCO2Level();
float voc = readVOCLevel();
// Exceedance detection logic
return (co2 > 800) || (voc > 0.5) || (readSmokeLevel() > 1000);
}
6. Optimization Techniques
- Preheating Treatment
void preheatSensor() {
Serial.println("Preheating sensor...");
for(int i = 0; i < 180; i++) { // 3 minutes preheating
delay(1000);
}
Serial.println("Preheating complete");
}
- Drift Compensation
float calibrateReading(float rawValue) {
// Subtract baseline value (to be calibrated periodically)
static float baseLine = 850.0;
return rawValue - baseLine;
}
- Deep Sleep
void deepSleepSavePower() {
esp_sleep_enable_timer_wakeup(300 * 1000000); // Sleep for 5 minutes
esp_deep_sleep_start();
}
7. Practical Operation Steps
-
Wiring Check
- Ensure the sensor operates at the appropriate voltage
- Check ground connections
- Confirm data line connections are correct
Calibration Process
- Power on in clean air
- Preheat for 30 minutes
- Record stable value as baseline
- Repeat calibration quarterly
Troubleshooting
- No change in value: Check wiring
- Value jumps: Add filtering capacitor
- Low readings: Check sensor lifespan
- High readings: Clean sensor surface
With the powerful processing capabilities and rich interfaces of the ESP32, gas sensors can build complete solutions ranging from simple detection to intelligent control.
ESP32 IoT CompassThree Days to Master Microcontrollers