The MQ-2 Gas Sensor is one of the most popular sensors for detecting gases like LPG, propane, methane, hydrogen, alcohol, and smoke. It works on the principle of resistance change—the sensor’s internal resistance decreases when exposed to gas, which changes the output voltage.
The MQ-2 module provides both:
In this tutorial, we will connect the MQ-2 sensor to ESP32 (GPIO 33 for analog reading) and monitor gas levels via the Serial Monitor.
// MQ-2 Gas Sensor with ESP32 DOIT DevKit v1
#define MQ2_PIN 33 // MQ-2 Analog output connected to GPIO 33
void setup() {
Serial.begin(115200);
Serial.println("MQ-2 Gas Sensor Test with ESP32");
}
void loop() {
int gasValue = analogRead(MQ2_PIN); // Read analog value
Serial.print("Gas Sensor Value: ");
Serial.println(gasValue);
// Simple threshold detection
if (gasValue > 2000) { // Adjust threshold based on calibration
Serial.println("Warning! Gas Detected ");
}
delay(1000); // 1 second delay
}
Define Pin
#define MQ2_PIN 33
MQ-2 analog pin connected to GPIO 33.
Setup
Serial.begin(115200);
Initialize Serial Monitor for output.
Read Sensor Value
int gasValue = analogRead(MQ2_PIN);
Reads raw ADC value (0–4095 for ESP32).
Print Data
Serial.print("Gas Sensor Value: ");
Serial.println(gasValue);
Displays gas level on Serial Monitor.
Threshold Detection
if (gasValue > 2000) {
Serial.println("Warning! Gas Detected");
}
If value exceeds threshold, a warning is printed.
MQ-2 Gas Sensor Test with ESP32
Gas Sensor Value: 350
Gas Sensor Value: 780
Gas Sensor Value: 2200
Warning! Gas Detected
Problem | Cause | Solution |
---|---|---|
Constant HIGH values | Sensor not warmed up | MQ-2 needs 24–48 hours initial burn-in |
Unstable readings | Power issues | Use stable 5V supply for best results |
Always LOW values | Wrong wiring | Double-check VCC, GND, AO connections |
Threshold too sensitive | Poor calibration | Adjust values experimentally |
Library error | Not needed | MQ-2 works with analogRead(), no library required |
The sensor’s resistance changes based on environment; calibration ensures accurate readings.
No ❌, it mainly detects LPG, propane, methane, hydrogen, smoke, and alcohol vapors.
At least 24 hours for initial burn-in, but 1–2 minutes for normal operation after that.
Yes ✅, but it only gives HIGH/LOW output based on threshold, not actual gas concentration.
Not really ❌, it’s better for indoor gas leak detection. For air quality, use sensors like MQ-135.