Gas leak detector
Read an MQ-2 gas sensor's concentration and alarm when it passes a threshold.
Sensors · Beginner
In a real product: Kitchen gas alarm (Smart home): Sounds an alarm when the gas concentration crosses a safe limit.
The MQ-2 senses flammable gases and smoke: a heated element's resistance drops as the gas concentration rises. The module gives an analog reading and a digital alarm output.
What you'll learn
- Reading a gas sensor module
- Using the module's comparator output (active low)
- Why real gas sensors need a warm-up time
How it works
AOUT goes to A0 and rises with the gas concentration. DOUT goes to pin 2 and is pulled LOW when the concentration passes the threshold set on the module's trimmer.
The loop prints the raw reading and lights the built-in LED while DOUT is LOW.
A real MQ-2 has a heater that needs a minute or more to warm up before the readings settle, and it should be calibrated in clean air.
Try this
- Raise the sensor's ppm slider past 1000 while it runs.
- Add a buzzer that beeps faster as the reading rises.
- Average the reading over 10 samples so a single spike does not trigger the alarm.
sketch.ino
// An MQ-2 gas sensor: AOUT on A0 (higher = more gas), DOUT on pin 2 (LOW = over the threshold).
const int GAS_ANALOG = A0;
const int GAS_DIGITAL = 2;
void setup() {
pinMode(GAS_DIGITAL, INPUT);
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
int reading = analogRead(GAS_ANALOG);
bool alarm = digitalRead(GAS_DIGITAL) == LOW;
Serial.print("Gas reading: ");
Serial.print(reading);
Serial.println(alarm ? " GAS ALARM" : " ok");
digitalWrite(LED_BUILTIN, alarm);
delay(500);
}