ATmega16 Fire & Gas Safety System with MQ-2, Flame Sensor, LCD & Exhaust Fan

Build an ATmega16 fire and gas safety system that watches an MQ-2 gas/smoke sensor, an IR flame sensor and an LM35 temperature sensor, shows the status on a 16×2 LCD, switches on an exhaust fan, closes a gas valve relay and sounds a latched alarm.

  • DifficultyAdvanced
  • Build time5–6 hours
  • Board / MCUATmega16 (8 MHz internal)
  • Parts15 items
  • CodeEmbedded C (AVR-GCC)

Need it ready-made? Buy Ready Project

This ATmega16 fire and gas safety system is a complete kitchen and workshop safety controller built around one 40-pin AVR chip. It watches three sensors at the same time: an MQ-2 module for LPG, smoke and other combustible gases, an IR flame sensor that sees an open flame, and an LM35 for room temperature. A 16×2 LCD shows the live gas level, temperature and system state, while a 2-channel relay module drives an exhaust fan and a gas solenoid valve (or a mains cut-off contactor).

When gas starts to build up, the fan switches on automatically and the buzzer gives a slow warning beep. If there is a flame, heavy gas or smoke, or a very high temperature, the system goes into a latched ALARM: the fan runs, the valve relay closes the gas supply, the red LED flashes and the buzzer sounds fast. The alarm stays on until the danger is gone and someone presses the RESET button, just like a real fire panel. It is a big combination project that teaches multi-channel ADC, sensor calibration, state machines, relay control and 4-bit LCD driving in plain AVR C.

Safety note: this is a learning project, not a certified gas or fire detector. Keep a certified smoke and LPG alarm installed, and let a qualified electrician do any 230V mains wiring.

ATmega16 fire and gas safety system on a breadboard with MQ-2 gas sensor, flame sensor, LM35, 16x2 LCD showing SAFE, 2-channel relay with exhaust fan, buzzer, red and green LEDs and push button

How It Works

  • Warm-up and auto-calibration: the MQ-2 heater needs about a minute to stabilise, so the LCD counts down 60 seconds while the LEDs blink. The ATmega16 then averages 200 readings from ADC0 in clean air and stores this as the baseline. All gas readings are shown as a rise above the baseline (for example Gas:+35), which makes the project work with any MQ-2 module.
  • Gas and smoke (PA0): the MQ-2 tin-dioxide element lowers its resistance when LPG, methane, propane, hydrogen or smoke reaches it, so the AOUT voltage rises. 16 samples are averaged every 100 ms to remove noise.
  • Temperature (PA1): the LM35 outputs 10 mV per °C. With the 5V AVCC reference each ADC step is about 4.9 mV, so the code converts it with temp = raw × 500 / 1023.
  • Flame (PD2): the flame module’s comparator output goes LOW when it sees the infrared light from a flame. The internal pull-up keeps the line HIGH otherwise.
  • Three states: SAFE (green LED, relays off), WARNING (gas rise of 80+ counts or 45 °C+: fan on and a slow beep) and ALARM (flame, gas rise of 220+ counts or 60 °C+: fan on, valve relay on, red LED flashing and a fast beep). All limits are #define values at the top of the code.
  • Latched alarm and silence: during an alarm, one press of the button mutes the buzzer for 60 seconds (an M appears on the LCD). After the sensors return to normal the alarm stays latched until you press the button again, so nobody misses a short event.
  • Fan run-on: after gas clears, the exhaust fan keeps running for 30 more seconds to push the remaining gas out of the room.

Components Required

  • ATmega16 microcontroller (40-pin DIP) – 1
  • USBasp programmer (10-pin to 6-pin adapter if needed) – 1
  • MQ-2 gas/smoke sensor module (with AOUT pin) – 1
  • IR flame sensor module (3-pin, DO output) – 1
  • LM35 temperature sensor (TO-92) – 1
  • 16×2 character LCD (HD44780) with 10 kΩ contrast pot – 1
  • 2-channel 5V relay module (opto-isolated) – 1
  • 12V DC exhaust fan (or small 5V fan for the demo) – 1
  • 12V solenoid gas valve (or any load for the demo) – 1
  • Active buzzer 5V + 2N2222 transistor + 1 kΩ resistor – 1 set
  • Red and green 5 mm LEDs with 220 Ω resistors – 1 each
  • Tactile push button (SILENCE / RESET) – 1
  • 10 kΩ resistor (RESET pull-up) and 100 nF capacitors – 1 and 3
  • 12V 2A adapter + LM7805 regulator (or 5V 2A supply) – 1
  • Large breadboard or perfboard and jumper wires – 1 set

Wiring Table

Part / pinATmega16 pinNotes
7805 output +5VVCC (10), AVCC (30)100 nF from each to GND; AREF (32) 100 nF to GND
GNDGND (11, 31)Common ground for sensors, relay module, LCD and 12V supply
RESETPin 910 kΩ to +5V (also to USBasp RESET)
MQ-2 AOUTPA0 / ADC0 (40)MQ-2 VCC to +5V (heater draws about 150 mA)
LM35 Vout (middle pin)PA1 / ADC1 (39)Left pin +5V, right pin GND (flat face towards you)
Flame sensor DOPD2 (16)Module VCC +5V, GND; set sensitivity with its blue pot
SILENCE / RESET buttonPD3 (17) and GNDInternal pull-up, no resistor needed
LCD RS / RW / ENPB0 (1) / GND / PB1 (2)LCD VSS GND, VDD +5V, V0 to 10 kΩ pot wiper
LCD D4, D5, D6, D7PB4, PB5, PB6, PB7 (5–8)D0–D3 unused; backlight A via 220 Ω to +5V, K to GND
Relay IN1 (exhaust fan)PC0 (22)Fan +12V through relay COM/NO
Relay IN2 (gas valve / cut-off)PC1 (23)Valve +12V through relay COM/NO
Relay module VCC / GND+5V / GNDActive-LOW inputs; set RELAY_ACTIVE_LOW 0 for active-HIGH boards
Buzzer driverPD5 (19)1 kΩ to 2N2222 base, emitter GND, buzzer between +5V and collector
Red ALARM LEDPD6 (20)Through 220 Ω, cathode to GND
Green SAFE LEDPD7 (21)Through 220 Ω, cathode to GND

Fuses: the code runs on the internal 8 MHz oscillator with JTAG disabled so all of PORTC is free: lfuse = 0xE4, hfuse = 0xD9. A fresh ATmega16 has JTAG enabled, which blocks PC2–PC5, so always set the fuses first.

Connection Diagram

The illustration above shows the parts laid out on a breadboard. It is a layout guide only, so follow the pin-accurate drawing below, which matches the wiring table.

ATmega16 Fire & Gas Safety System – Pin-Accurate Wiring ATmega16 VCC/AVCC (10,30) +5V from 7805; AREF (32) via 100 nF to GND GND (11,31) Common GND for all modules and supplies PA0 / ADC0 (40) MQ-2 module AOUT PA1 / ADC1 (39) LM35 middle pin (Vout) PB0 (1) LCD RS (pin 4); LCD RW (pin 5) to GND PB1 (2) LCD EN (pin 6) PB4-PB7 (5-8) LCD D4-D7 (pins 11-14) PC0 (22) Relay IN1 – exhaust fan PC1 (23) Relay IN2 – gas valve / cut-off PD2 / INT0 (16) Flame sensor DO (LOW = flame) PD3 (17) SILENCE/RESET button to GND PD5 (19) 1 kΩ to 2N2222 base; buzzer on collector PD6 (20) 220 Ω to red ALARM LED PD7 (21) 220 Ω to green SAFE LED RESET (9): 10 kΩ to +5V. Program with USBasp: MOSI PB5, MISO PB6, SCK PB7, RESET.
Pin-accurate connection diagram for the ATmega16 fire and gas safety system.

Code

The firmware is plain AVR C with no external libraries (about 1.9 KB of flash). Save it as main.c, then compile and flash it with avr-gcc and a USBasp:

avr-gcc -mmcu=atmega16 -Os -o main.elf main.c
avr-objcopy -O ihex -R .eeprom main.elf main.hex
avrdude -c usbasp -p m16 -U lfuse:w:0xE4:m -U hfuse:w:0xD9:m
avrdude -c usbasp -p m16 -U flash:w:main.hex:i

You can also use Microchip Studio: create a GCC C project for the ATmega16, paste the code and build. Keep F_CPU at 8000000 to match the fuses.

/*
 * ATmega16 Fire & Gas Safety System
 * MQ-2 gas/smoke sensor + IR flame sensor + LM35 temperature sensor,
 * 16x2 LCD, 2-channel relay (exhaust fan + gas valve / mains cut-off),
 * buzzer, LEDs and a SILENCE / RESET button.
 * ardiunoprojecthub.online
 *
 * MCU   : ATmega16 @ 8 MHz internal oscillator
 * Fuses : lfuse=0xE4 (internal 8 MHz), hfuse=0xD9 (JTAG off so PORTC is free)
 *
 * Pins
 *   MQ-2 AOUT        -> PA0 (ADC0)
 *   LM35 Vout        -> PA1 (ADC1)
 *   Flame sensor DO  -> PD2 (LOW = flame seen, internal pull-up on)
 *   SILENCE button   -> PD3 to GND (internal pull-up)
 *   LCD 16x2 4-bit   : RS=PB0, EN=PB1, D4=PB4, D5=PB5, D6=PB6, D7=PB7, RW=GND
 *   Relay CH1 (fan)  -> PC0
 *   Relay CH2 (valve)-> PC1
 *   Buzzer (active)  -> PD5 (via 2N2222 or direct if < 20 mA)
 *   Red LED ALARM    -> PD6 (220 ohm)
 *   Green LED SAFE   -> PD7 (220 ohm)
 *   AVCC -> 5V, AREF -> 100 nF to GND (AVCC used as ADC reference)
 *
 * States
 *   SAFE    : green LED, relays off.
 *   WARNING : gas rising or temperature high -> exhaust fan ON, slow beep.
 *   ALARM   : flame, heavy gas/smoke or very high temperature ->
 *             fan ON, gas valve relay CLOSES supply, fast beep, red LED.
 *   ALARM is latched: once conditions are safe again, press SILENCE/RESET
 *   to return to SAFE. While in ALARM, SILENCE mutes the buzzer for 60 s.
 */
#define F_CPU 8000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <stdint.h>
#include <stdlib.h>

/* ---------- user settings ---------- */
#define WARMUP_S        60     /* MQ-2 heater warm-up time            */
#define GAS_WARN_DELTA  80     /* ADC counts above clean-air baseline */
#define GAS_ALARM_DELTA 220
#define TEMP_WARN_C     45
#define TEMP_ALARM_C    60
#define FAN_RUNON_S     30     /* fan keeps running after gas clears  */
#define SILENCE_S       60
#define RELAY_ACTIVE_LOW 1     /* most blue relay modules are active-LOW */

/* ---------- LCD (HD44780 4-bit on PORTB) ---------- */
#define LCD_RS PB0
#define LCD_EN PB1

static void lcd_pulse(void)
{
    PORTB |= (1 << LCD_EN); _delay_us(1);
    PORTB &= ~(1 << LCD_EN); _delay_us(50);
}
static void lcd_nibble(uint8_t n)
{
    PORTB = (PORTB & 0x0F) | (n & 0xF0);
    lcd_pulse();
}
static void lcd_byte(uint8_t b, uint8_t rs)
{
    if (rs) PORTB |= (1 << LCD_RS); else PORTB &= ~(1 << LCD_RS);
    lcd_nibble(b);
    lcd_nibble(b << 4);
    if (!rs && b < 4) _delay_ms(2);
}
static void lcd_cmd(uint8_t c)  { lcd_byte(c, 0); }
static void lcd_char(char c)    { lcd_byte((uint8_t)c, 1); }
static void lcd_goto(uint8_t col, uint8_t row) { lcd_cmd(0x80 | (row ? 0x40 : 0x00) | col); }
static void lcd_print(const char *s) { while (*s) lcd_char(*s++); }
static void lcd_line(uint8_t row, const char *s)
{   /* print a full 16-char line, padding with spaces (no flicker) */
    uint8_t i = 0;
    lcd_goto(0, row);
    while (*s && i < 16) { lcd_char(*s++); i++; }
    while (i++ < 16) lcd_char(' ');
}
static void lcd_init(void)
{
    DDRB |= 0xF3;                 /* PB0, PB1, PB4..PB7 outputs */
    _delay_ms(50);
    PORTB &= ~(1 << LCD_RS);
    lcd_nibble(0x30); _delay_ms(5);
    lcd_nibble(0x30); _delay_us(150);
    lcd_nibble(0x30); _delay_us(150);
    lcd_nibble(0x20);             /* 4-bit mode */
    lcd_cmd(0x28);                /* 2 lines, 5x8 font */
    lcd_cmd(0x0C);                /* display on, cursor off */
    lcd_cmd(0x06);                /* entry mode */
    lcd_cmd(0x01);                /* clear */
}

/* ---------- ADC ---------- */
static void adc_init(void)
{
    ADMUX  = (1 << REFS0);                                 /* AVCC ref */
    ADCSRA = (1 << ADEN) | (1 << ADPS2) | (1 << ADPS1);    /* 8 MHz/64 = 125 kHz */
}
static uint16_t adc_read(uint8_t ch)
{
    ADMUX = (1 << REFS0) | (ch & 0x07);
    _delay_us(20);
    ADCSRA |= (1 << ADSC);
    while (ADCSRA & (1 << ADSC));
    return ADC;
}
static uint16_t adc_avg(uint8_t ch, uint8_t n)
{
    uint32_t sum = 0;
    for (uint8_t i = 0; i < n; i++) sum += adc_read(ch);
    return (uint16_t)(sum / n);
}

/* ---------- outputs ---------- */
static void relay(uint8_t pin, uint8_t on)
{
#if RELAY_ACTIVE_LOW
    if (on) PORTC &= ~(1 << pin); else PORTC |= (1 << pin);
#else
    if (on) PORTC |= (1 << pin); else PORTC &= ~(1 << pin);
#endif
}
#define FAN   PC0
#define VALVE PC1
#define BUZ_ON()   (PORTD |=  (1 << PD5))
#define BUZ_OFF()  (PORTD &= ~(1 << PD5))
#define RED(x)     ((x) ? (PORTD |= (1 << PD6)) : (PORTD &= ~(1 << PD6)))
#define GREEN(x)   ((x) ? (PORTD |= (1 << PD7)) : (PORTD &= ~(1 << PD7)))
#define FLAME_SEEN()   (!(PIND & (1 << PD2)))
#define BTN_PRESSED()  (!(PIND & (1 << PD3)))

enum { SAFE, WARNING, ALARM };

static void beep(uint16_t ms) { BUZ_ON(); while (ms--) _delay_ms(1); BUZ_OFF(); }

int main(void)
{
    char num[7];

    /* I/O setup */
    DDRC |= (1 << FAN) | (1 << VALVE);
    relay(FAN, 0); relay(VALVE, 0);
    DDRD |= (1 << PD5) | (1 << PD6) | (1 << PD7);
    DDRD &= ~((1 << PD2) | (1 << PD3));
    PORTD |= (1 << PD2) | (1 << PD3);           /* pull-ups */

    lcd_init();
    adc_init();

    /* ---- warm-up of the MQ-2 heater ---- */
    lcd_line(0, "Fire&Gas Safety");
    for (int s = WARMUP_S; s > 0; s--) {
        itoa(s, num, 10);
        lcd_line(1, "");
        lcd_goto(0, 1); lcd_print("Warm-up "); lcd_print(num); lcd_print(" s");
        RED(s & 1); GREEN(!(s & 1));
        _delay_ms(1000);
    }

    /* ---- learn clean-air baseline ---- */
    lcd_line(1, "Calibrating...");
    uint32_t sum = 0;
    for (uint16_t i = 0; i < 200; i++) { sum += adc_read(0); _delay_ms(5); }
    uint16_t baseline = (uint16_t)(sum / 200);
    RED(0); GREEN(1);
    beep(100);

    uint8_t  state = SAFE, latched = 0;
    uint16_t fan_runon = 0, silence = 0;   /* in 100 ms ticks */
    uint8_t  tick = 0, btn_prev = 0;

    for (;;) {
        /* ---- read sensors (every 100 ms) ---- */
        uint16_t gas  = adc_avg(0, 16);
        int16_t  diff = (int16_t)gas - (int16_t)baseline;
        if (diff < 0) diff = 0;
        uint16_t traw = adc_avg(1, 16);
        int16_t  temp = (int16_t)((traw * 500UL) / 1023);   /* LM35: 10 mV/C */
        uint8_t  flame = FLAME_SEEN();

        /* ---- decide state ---- */
        uint8_t now;
        if (flame || diff >= GAS_ALARM_DELTA || temp >= TEMP_ALARM_C) now = ALARM;
        else if (diff >= GAS_WARN_DELTA || temp >= TEMP_WARN_C)      now = WARNING;
        else                                                          now = SAFE;

        if (now == ALARM) { latched = 1; }
        if (latched) state = ALARM; else state = now;

        /* ---- button: silence buzzer or reset latched alarm ---- */
        uint8_t btn = BTN_PRESSED();
        if (btn && !btn_prev) {
            if (latched && now != ALARM) { latched = 0; state = now; silence = 0; beep(60); }
            else if (state == ALARM) { silence = SILENCE_S * 10; }
        }
        btn_prev = btn;
        if (silence) silence--;

        /* ---- outputs ---- */
        if (state != SAFE || diff >= GAS_WARN_DELTA) fan_runon = FAN_RUNON_S * 10;
        else if (fan_runon) fan_runon--;
        relay(FAN, fan_runon > 0);
        relay(VALVE, state == ALARM);           /* close gas / cut supply */

        GREEN(state == SAFE);
        if (state == ALARM)        { RED(tick & 2); if (!silence && (tick & 2)) BUZ_ON(); else BUZ_OFF(); }
        else if (state == WARNING) { RED(tick < 2); if (tick == 0) BUZ_ON(); else BUZ_OFF(); }
        else                       { RED(0); BUZ_OFF(); }

        /* ---- LCD every 500 ms ---- */
        if (tick % 5 == 0) {
            const char *msg;
            if (state == ALARM)
                msg = flame ? "!! FIRE ALARM !!" : (diff >= GAS_ALARM_DELTA ? "!! GAS  ALARM !!" :
                      (temp >= TEMP_ALARM_C ? "!! HEAT ALARM !!" : "ALARM-press RST "));
            else if (state == WARNING) msg = "WARNING  Fan ON ";
            else msg = fan_runon ? "SAFE    Fan ON  " : "SAFE  All normal";
            lcd_line(0, msg);

            /* line 2: "Gas:+123 T:31C F" */
            itoa(diff, num, 10);
            lcd_goto(0, 1);
            lcd_print("Gas:+"); lcd_print(num); lcd_print("   ");
            lcd_goto(9, 1);
            itoa(temp, num, 10);
            lcd_print("T:"); lcd_print(num); lcd_print("C");
            lcd_print(temp < 10 ? "  " : (temp < 100 ? " " : ""));
            lcd_goto(15, 1);
            lcd_char(flame ? 'F' : (silence ? 'M' : ' '));
        }

        if (++tick >= 10) tick = 0;
        _delay_ms(100 - 20);   /* ~100 ms loop including ADC time */
    }
}

Testing and Calibration

  • Power up in clean air. After the warm-up the LCD should read SAFE All normal with a gas value close to +0 and the room temperature.
  • Gas test: hold an unlit lighter near the MQ-2 and press its gas button briefly (do not light it). The gas value rises, the fan relay clicks on (WARNING) and, with more gas, the system goes to GAS ALARM and the valve relay turns on.
  • Flame test: light a candle about 30–50 cm in front of the flame sensor. Its DO LED lights and the LCD shows FIRE ALARM. Adjust the module’s pot so normal room light does not trigger it.
  • Heat test: warm the LM35 gently with your fingers or a hair dryer on low to see the temperature go up; lower TEMP_WARN_C temporarily to test the warning.
  • Press the button during an alarm to mute it, then again after the reading is normal to reset. Tune GAS_WARN_DELTA and GAS_ALARM_DELTA to suit your room.

Troubleshooting

ProblemFix
LCD shows black boxes or nothingTurn the 10 kΩ contrast pot. Check RW is tied to GND and the D4–D7 lines go to PB4–PB7 in order.
LCD garbled or code runs very slowlyThe fuses are still at 1 MHz or the clock does not match F_CPU. Program lfuse 0xE4 and hfuse 0xD9.
Relays click the wrong way (on when SAFE)Your relay board is active-HIGH. Change RELAY_ACTIVE_LOW to 0 and rebuild.
Goes to GAS ALARM right after startIt calibrated in dirty air or the MQ-2 is new. Burn in a new sensor for 24–48 hours, then reset the ATmega16 in fresh air.
FIRE ALARM in sunlight or bright lampSunlight contains infrared. Turn the flame module’s pot to lower sensitivity and point it away from windows.
Temperature reads 0 or jumps a lotCheck the LM35 pin order and add a 100 nF capacitor from its output to GND. Keep its wires away from the relay wires.
Controller resets when the fan or valve switchesFeed the 12V loads from their own supply, keep only GND common, add a flyback diode across the solenoid valve and a 470 µF capacitor on the 5V rail.

Ideas to Extend

  • Add a SIM800L GSM module on the ATmega16 UART (PD0/PD1) to send an SMS on alarm.
  • Log alarm events with a time stamp using a DS1307 RTC and the internal EEPROM.
  • Add a second MQ-2 in another room on ADC2 and show which zone is in alarm.

Leave a Comment