// The MQ-2's analog output (AO) const int GAS_PIN = A0; // Buzzer and the two LEDs' pins const int BUZZER_PIN = 8; const int GREEN_LED = 11; const int RED_LED = 12; // Heater warm-up time (ms) const unsigned long WARM_UP = 30000; // The alarm sounds once the reading rises // this far over clean air (0-1023) const int ALARM_RISE = 150; // It stops once back down to this const int CLEAR_RISE = 100; // Time between readings (ms) const unsigned long MEASURE_EVERY = 1000; // Siren pitch (Hz) const int ALARM_HZ = 3000; int baseline = 0; bool alarmOn = false; bool beeping = false; unsigned long alarmStart = 0; unsigned long lastMeasure = 0; void setup() { pinMode(BUZZER_PIN, OUTPUT); pinMode(GREEN_LED, OUTPUT); pinMode(RED_LED, OUTPUT); Serial.begin(9600); // Green LED blinks while warming up Serial.println("Sensor warming up, wait 30 s..."); unsigned long start = millis(); while (millis() - start < WARM_UP) { digitalWrite(GREEN_LED, (millis() / 500) % 2 ? HIGH : LOW); } // Clean air value: mean of 10 readings long total = 0; for (int i = 0; i < 10; i++) { total += analogRead(GAS_PIN); delay(200); } baseline = total / 10; Serial.print("Clean air value: "); Serial.println(baseline); // Close to 0: the sensor has no power if (baseline < 10) { Serial.println("Cannot read the sensor, check the wires."); digitalWrite(GREEN_LED, LOW); while (true) {} } digitalWrite(GREEN_LED, HIGH); Serial.println("Alarm armed."); } // Smoke alarm pattern (T3): three half- // second beeps, then 1.5 s of quiet void updateAlarm() { bool beep = false; if (alarmOn) { // Where we are in the 4 s cycle unsigned long t = (millis() - alarmStart) % 4000; beep = t < 2500 && (t / 500) % 2 == 0; } // tone() only when the sound changes if (beep != beeping) { beeping = beep; if (beep) { tone(BUZZER_PIN, ALARM_HZ); } else { noTone(BUZZER_PIN); } } digitalWrite(RED_LED, beep ? HIGH : LOW); digitalWrite(GREEN_LED, alarmOn ? LOW : HIGH); } void loop() { if (millis() - lastMeasure >= MEASURE_EVERY) { lastMeasure = millis(); int gas = analogRead(GAS_PIN); int rise = gas - baseline; Serial.print("Gas: "); Serial.print(gas); Serial.print(" | Rise: "); Serial.println(rise); // Two thresholds: no flicker at edge if (!alarmOn && rise >= ALARM_RISE) { alarmOn = true; alarmStart = millis(); Serial.println("ALARM! Smoke or gas detected."); } else if (alarmOn && rise <= CLEAR_RISE) { alarmOn = false; Serial.println("Air is clear, alarm stopped."); } } updateAlarm(); }