ATmega16 Digital Metronome with 4-Digit 7-Segment Display, Tap Tempo & Accent Beat

Connection diagram of the ATmega16 digital metronome with 4-digit 7-segment display, BC547 digit drivers, five push buttons, piezo buzzer and beat LEDs

Build an ATmega16 digital metronome that shows the tempo (30–250 BPM) and the beat number on a 4-digit 7-segment display, clicks a piezo with an accented first beat, flashes two LEDs and supports tap tempo and 1–9 beats per bar.

  • DifficultyEasy
  • Build time2–3 hours
  • Board / MCUATmega16 (8 MHz internal)
  • Parts12 items
  • CodeEmbedded C (AVR-GCC)

Need it ready-made? Buy Ready Project

A metronome gives musicians a steady beat to practise with. This ATmega16 digital metronome shows the tempo in beats per minute (BPM) on a bright 4-digit 7-segment display, makes a sharp click on a piezo buzzer for every beat and gives the first beat of each bar a higher, accented click. Two LEDs flash with the beat, so you can also follow it by eye in a noisy room.

It is a great small project for learning ATmega16 timers: Timer0 creates an exact 1 ms tick that multiplexes the display and times the beats, and Timer1 makes the click tone in hardware on the OC1A pin. You can set the tempo from 30 to 250 BPM with UP and DOWN buttons, choose 1 to 9 beats per bar, or simply tap the TAP button a few times at the speed of a song. The settings are saved in EEPROM.

Connection diagram of the ATmega16 digital metronome with 4-digit 7-segment display, BC547 digit drivers, five push buttons, piezo buzzer and beat LEDs

How It Works

  • 1 ms system tick: Timer0 runs in CTC mode with a prescaler of 64 and OCR0 = 124, so with the 8 MHz internal clock it interrupts exactly 1000 times per second (8 000 000 / 64 / 125).
  • Display multiplexing: on each tick the interrupt switches off all four digits, puts the segment pattern of the next digit on PORTC and turns on that digit’s BC547 transistor. Each digit is lit for 1 ms out of every 4 ms (250 Hz), which looks completely steady to the eye.
  • Beat timing: the beat interval is 60000 / BPM milliseconds (500 ms at 120 BPM). The same interrupt counts milliseconds and fires a beat when the interval is reached. Because the counting happens inside the ISR, button handling in the main loop can never make the beat drift.
  • Click sound: Timer1 in CTC mode toggles the OC1A pin (PD5) in hardware. OCR1A = 249 gives 2000 Hz for the accented first beat and OCR1A = 499 gives 1000 Hz for the other beats. After 30 ms the interrupt disconnects OC1A, so you hear a short, clean click.
  • Beats per bar: the BEATS button cycles from 1 to 9. The first digit shows the current beat (1, 2, 3, 4, 1 …) while running. When stopped, it shows the beats-per-bar setting with its decimal point lit.
  • Tap tempo: press TAP at least twice in time with the music. The ATmega16 measures the gap between taps (240–2000 ms), averages the last few gaps and converts it to BPM.
  • Memory: 3 seconds after your last change, BPM and beats per bar are written to the internal EEPROM with eeprom_update_byte(), which only writes when the value really changed.

Components Required

  • ATmega16 microcontroller (40-pin DIP) – 1
  • USBasp programmer (10-pin to 6-pin adapter if needed) – 1
  • 4-digit 7-segment display, common cathode, 0.56 inch (e.g. 5641AS) – 1
  • BC547 NPN transistors (digit drivers) – 4
  • 1 kΩ resistors (transistor bases) – 4
  • 220 Ω resistors (8 segments + 2 LEDs) – 10
  • Passive piezo buzzer + 100 Ω series resistor – 1
  • 5 mm LEDs, red and green – 1 each
  • 12 mm tactile push buttons (UP, DOWN, START/STOP, BEATS, TAP) – 5
  • 10 kΩ resistor (RESET pull-up) and 100 nF capacitors – 1 and 2
  • 5 V supply: USB 5 V or 9 V battery with LM7805 – 1
  • Breadboard or perfboard and jumper wires – 1 set

Wiring Table

Part / pinATmega16 pinNotes
+5 VVCC (10), AVCC (30)100 nF from each to GND
GNDGND (11, 31)Common ground for everything
RESETPin 910 kΩ to +5 V (also to USBasp RESET)
Segment a, b, c, dPC0, PC1, PC2, PC3 (22–25)Each through a 220 Ω resistor
Segment e, f, g, dpPC4, PC5, PC6, PC7 (26–29)Each through a 220 Ω resistor
Digit 1 (beat) cathodeBC547 collector, base 1 kΩ to PB0 (1)Emitter to GND
Digit 2 (hundreds) cathodeBC547 collector, base 1 kΩ to PB1 (2)Emitter to GND
Digit 3 (tens) cathodeBC547 collector, base 1 kΩ to PB2 (3)Emitter to GND
Digit 4 (units) cathodeBC547 collector, base 1 kΩ to PB3 (4)Emitter to GND
UP / DOWN buttonsPA0 (40) / PA1 (39)Other leg to GND, internal pull-ups
START/STOP / BEATS / TAPPA2 (38) / PA3 (37) / PA4 (36)Other leg to GND, internal pull-ups
Passive piezo (+)PD5 / OC1A (19)Through 100 Ω; piezo (–) to GND
Red LED (accent)PD6 (20)220 Ω, cathode to GND
Green LED (beat)PD7 (21)220 Ω, cathode to GND
USBasp MOSI / MISO / SCKPB5 (6) / PB6 (7) / PB7 (8)Left free for programming

Pin check: PC2–PC5 are also the JTAG pins (TCK, TMS, TDO, TDI). A new ATmega16 has JTAG enabled, so you must program the high fuse to 0xD9 to free them; the code also writes the JTD bit twice at start-up. PD5 is the OC1A pin, so Timer1 can make the tone without any CPU work. Use a passive piezo; an active buzzer only gives one fixed tone.

Connection Diagram

The diagram above shows how the display, transistors, buttons and sound parts connect to the ATmega16. The drawing below lists every pin exactly as used in the code.

ATmega16 Digital Metronome – Pin-Accurate Wiring ATmega16 PA0 (40) UP button → GND PA1 (39) DOWN button → GND PA2 (38) START / STOP button → GND PA3 (37) BEATS button → GND (1–9 beats per bar) PA4 (36) TAP tempo button → GND PB0–PB3 (1–4) 1 kΩ → BC547 base; collector → digit 1–4 cathode; emitter → GND PC0–PC6 (22–28) 220 Ω → segments a, b, c, d, e, f, g PC7 (29) 220 Ω → segment dp (decimal point) PD5 (19) OC1A → 100 Ω → piezo (+), piezo (–) → GND PD6 (20) 220 Ω → red LED (accent, beat 1) → GND PD7 (21) 220 Ω → green LED (every beat) → GND RESET (9) 10 kΩ → 5 V and USBasp RESET VCC 10 / AVCC 30 +5 V, 100 nF to GND at each pin GND 11 / 31 Common GND Program hfuse 0xD9 (JTAG off) first, otherwise segments c, d, e and f on PC2–PC5 stay dark or dim. Display: digit 1 = beat number (dot lit when stopped = beats-per-bar setting), digits 2–4 = BPM.
Pin-accurate connection diagram for the ATmega16 digital metronome.

Code

The program is written in plain AVR C for AVR-GCC (Microchip Studio, or avr-gcc on Linux / WinAVR on Windows). It was compile-checked for the ATmega16: about 1.7 KB of flash and 30 bytes of RAM.

/*
 * ATmega16 Digital Metronome with 4-Digit 7-Segment Display
 * Arduino Project Hub - https://ardiunoprojecthub.online
 *
 * MCU    : ATmega16, internal 8 MHz RC oscillator
 * Fuses  : lfuse 0xE4 (int. 8 MHz), hfuse 0xD9 (JTAG off - PORTC is free)
 * Build  : avr-gcc -mmcu=atmega16 -DF_CPU=8000000UL -Os -o metronome.elf atmega16_metronome.c
 *
 * Display: 4-digit common-cathode 7-segment
 *          segments a..g, dp -> PC0..PC7 (through 220 ohm resistors)
 *          digit 1..4 cathodes -> BC547 NPN transistors driven from PB0..PB3 (1k base)
 *          digit 1 = beat number (running) or beats per bar (stopped)
 *          digits 2-4 = tempo in BPM (30..250)
 * Buttons: PA0 UP, PA1 DOWN, PA2 START/STOP, PA3 BEATS (1..9), PA4 TAP (to GND, pull-ups on)
 * Sound  : passive piezo buzzer on PD5 (OC1A) - high click on beat 1, low click on others
 * LEDs   : PD6 red = accent (beat 1), PD7 green = every beat (220 ohm resistors)
 */
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/eeprom.h>
#include <util/delay.h>
#include <stdint.h>

#define BPM_MIN     30
#define BPM_MAX     250
#define CLICK_MS    30          /* length of each click                 */
#define TONE_HIGH   249         /* OCR1A for 2000 Hz (accent)           */
#define TONE_LOW    499         /* OCR1A for 1000 Hz (normal beat)      */
#define LED_MS      80          /* how long the beat LEDs stay on       */

/* Segment patterns for 0-9, bit0 = a ... bit6 = g (common cathode) */
static const uint8_t SEG[10] = {
    0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F
};
#define SEG_BLANK 0x00
#define SEG_DP    0x80

/* Settings saved in EEPROM */
uint8_t EEMEM ee_bpm   = 120;
uint8_t EEMEM ee_beats = 4;

/* Shared with the 1 ms timer interrupt */
static volatile uint8_t  disp[4];          /* raw segment bytes per digit */
static volatile uint32_t ms_count = 0;     /* milliseconds since start    */
static volatile uint16_t beat_interval;    /* ms between beats            */
static volatile uint16_t beat_timer = 0;   /* ms since last beat          */
static volatile uint8_t  running = 0;
static volatile uint8_t  beat_no = 0;      /* 1..beats while running      */
static volatile uint8_t  beats_per_bar;
static volatile uint8_t  click_left = 0;   /* ms of click remaining       */
static volatile uint8_t  led_left = 0;     /* ms of LED flash remaining   */
static volatile uint8_t  refresh = 0;      /* ask main loop to redraw     */

static uint8_t bpm;

/* ---------- sound and beat (called from the ISR) ---------- */
static void start_click(uint8_t accent)
{
    OCR1A  = accent ? TONE_HIGH : TONE_LOW;
    TCNT1  = 0;
    TCCR1A = (1 << COM1A0);                /* toggle OC1A on compare match */
    click_left = CLICK_MS;

    PORTD |= (1 << PD7);                   /* green LED on every beat      */
    if (accent) PORTD |= (1 << PD6);       /* red LED on beat 1            */
    led_left = LED_MS;
}

static void do_beat(void)
{
    beat_no++;
    if (beat_no > beats_per_bar) beat_no = 1;
    /* with 1 beat per bar every beat is a normal click (no accent) */
    start_click(beat_no == 1 && beats_per_bar > 1);
    refresh = 1;
}

/* ---------- Timer0 compare: runs every 1 ms ---------- */
ISR(TIMER0_COMP_vect)
{
    static uint8_t digit = 0;

    /* 1. multiplex one digit per interrupt (250 Hz per digit, no flicker) */
    PORTB &= 0xF0;                         /* all digits off               */
    PORTC  = disp[digit];                  /* load segments                */
    PORTB |= (1 << digit);                 /* switch on this digit         */
    if (++digit > 3) digit = 0;

    /* 2. time keeping */
    ms_count++;

    /* 3. beat generator - timed inside the ISR so it never drifts */
    if (running) {
        if (++beat_timer >= beat_interval) {
            beat_timer = 0;
            do_beat();
        }
    }

    /* 4. end the click and the LED flash */
    if (click_left && --click_left == 0) {
        TCCR1A = 0;                        /* disconnect OC1A              */
        PORTD &= ~(1 << PD5);              /* leave piezo pin low          */
    }
    if (led_left && --led_left == 0) {
        PORTD &= ~((1 << PD6) | (1 << PD7));
    }
}

static uint32_t millis(void)
{
    uint32_t m;
    cli(); m = ms_count; sei();
    return m;
}

/* ---------- display ---------- */
static void show(void)
{
    uint8_t d[4];
    uint8_t lead = running ? beat_no : beats_per_bar;

    d[0] = SEG[lead % 10];
    if (!running) d[0] |= SEG_DP;          /* dot = stopped, setting mode  */
    d[1] = (bpm >= 100) ? SEG[bpm / 100] : SEG_BLANK;
    d[2] = SEG[(bpm / 10) % 10];
    d[3] = SEG[bpm % 10];

    for (uint8_t i = 0; i < 4; i++) disp[i] = d[i];   /* byte writes are atomic */
}

static void set_bpm(int16_t v)
{
    if (v < BPM_MIN) v = BPM_MIN;
    if (v > BPM_MAX) v = BPM_MAX;
    bpm = (uint8_t)v;
    uint16_t iv = 60000U / bpm;            /* 120 BPM -> 500 ms            */
    cli(); beat_interval = iv; sei();
}

static void save_settings(void)
{
    eeprom_update_byte(&ee_bpm, bpm);      /* only writes if value changed */
    eeprom_update_byte(&ee_beats, beats_per_bar);
}

/* ---------- buttons ---------- */
#define BTN_UP    0
#define BTN_DOWN  1
#define BTN_START 2
#define BTN_BEATS 3
#define BTN_TAP   4

static uint8_t pressed(uint8_t b) { return !(PINA & (1 << b)); }

int main(void)
{
    /* turn JTAG off in software too (needs two writes within 4 cycles) */
    MCUCSR |= (1 << JTD);
    MCUCSR |= (1 << JTD);

    DDRC  = 0xFF; PORTC = 0x00;            /* segments                     */
    DDRB |= 0x0F; PORTB &= 0xF0;           /* digit transistors            */
    DDRD |= (1 << PD5) | (1 << PD6) | (1 << PD7);
    DDRA &= ~0x1F; PORTA |= 0x1F;          /* buttons with pull-ups        */

    /* load saved settings (first power-up: EEPROM is 0xFF) */
    uint8_t b = eeprom_read_byte(&ee_bpm);
    uint8_t n = eeprom_read_byte(&ee_beats);
    if (b < BPM_MIN || b > BPM_MAX) b = 120;
    if (n < 1 || n > 9) n = 4;
    beats_per_bar = n;
    set_bpm(b);

    /* Timer0: CTC, 8 MHz / 64 / 125 = 1 kHz interrupt */
    TCCR0 = (1 << WGM01) | (1 << CS01) | (1 << CS00);
    OCR0  = 124;
    TIMSK |= (1 << OCIE0);

    /* Timer1: CTC (top OCR1A), prescaler 8 -> 1 MHz; f = 1 MHz / (2*(OCR1A+1)) */
    TCCR1A = 0;
    TCCR1B = (1 << WGM12) | (1 << CS11);

    sei();
    show();

    uint8_t  last = 0x1F;                  /* previous raw button state    */
    uint32_t t_press = 0, t_repeat = 0, t_change = 0;
    uint32_t last_tap = 0, tap_sum = 0;
    uint8_t  tap_count = 0, dirty = 0;

    while (1) {
        uint32_t now = millis();
        uint8_t  cur = PINA & 0x1F;

        if (cur != last) {                 /* a button changed state       */
            _delay_ms(20);                 /* simple debounce              */
            cur = PINA & 0x1F;
            uint8_t down = last & ~cur;    /* bits that just went LOW      */
            last = cur;
            now = millis();

            if (down & (1 << BTN_UP))   { set_bpm(bpm + 1); t_press = now; t_repeat = now; dirty = 1; }
            if (down & (1 << BTN_DOWN)) { set_bpm(bpm - 1); t_press = now; t_repeat = now; dirty = 1; }

            if (down & (1 << BTN_START)) {
                cli();
                running = !running;
                beat_no = 0;
                beat_timer = 0;
                sei();
                if (running) { cli(); do_beat(); sei(); }   /* first click at once */
            }

            if (down & (1 << BTN_BEATS)) {
                cli();
                if (++beats_per_bar > 9) beats_per_bar = 1;
                beat_no = 0;               /* restart the bar on beat 1    */
                sei();
                dirty = 1;
            }

            if (down & (1 << BTN_TAP)) {
                uint32_t gap = now - last_tap;
                last_tap = now;
                if (gap >= 240 && gap <= 2000) {   /* 250..30 BPM range   */
                    tap_sum += gap;
                    tap_count++;
                    set_bpm((int16_t)(60000UL * tap_count / tap_sum));
                    if (tap_count >= 4) { tap_sum = tap_sum / tap_count * 3; tap_count = 3; }
                    dirty = 1;
                } else {                   /* first tap or too slow: start over */
                    tap_sum = 0; tap_count = 0;
                }
            }
            t_change = now;
            show();
        }

        /* auto-repeat: hold UP/DOWN 500 ms, then 10 steps per second */
        if ((pressed(BTN_UP) || pressed(BTN_DOWN)) &&
            now - t_press > 500 && now - t_repeat > 100) {
            set_bpm(pressed(BTN_UP) ? bpm + 1 : bpm - 1);
            t_repeat = now;
            dirty = 1;
            t_change = now;
            show();
        }

        if (refresh) { refresh = 0; show(); }

        /* save to EEPROM 3 s after the last change (saves EEPROM wear) */
        if (dirty && now - t_change > 3000) {
            save_settings();
            dirty = 0;
        }
    }
}

Compile, Set Fuses and Upload

Connect the USBasp to MOSI, MISO, SCK, RESET, VCC and GND, then run these commands. The fuse values select the internal 8 MHz oscillator (lfuse 0xE4) and turn JTAG off (hfuse 0xD9).

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

Using the Metronome

  • Set the tempo: press UP or DOWN to change the BPM by 1. Hold the button for half a second to change it quickly (10 steps per second).
  • Start and stop: press START/STOP. The first click comes at once, and the first digit counts the beats of the bar.
  • Change the bar: press BEATS to choose 2 for marches, 3 for waltzes, 4 for most pop songs, or 1 for no accent at all.
  • Tap tempo: tap TAP four or five times along with a song and the display jumps to its tempo.
  • Power off: your last tempo and bar setting come back the next time you switch on.

Troubleshooting

ProblemFix
Segments c, d, e or f never lightJTAG is still enabled. Program hfuse to 0xD9 (JTAGEN unprogrammed) and power-cycle the chip.
Tempo is a little too fast or slowThe internal RC oscillator is about ±3 % out of the box. Write a calibration byte to OSCCAL, or use an 8 MHz crystal with lfuse 0xFF.
Display looks dim or ghost segments appearCheck that each digit uses its own BC547 and that the segment resistors are 220 Ω (not 1 kΩ). A display with common anode needs PNP drivers and inverted code.
No sound from the piezoIt must be a passive piezo on PD5 (OC1A). An active buzzer, or one wired to another pin, will not work with the hardware tone.
Buttons change the value twiceUse proper tactile switches; the code debounces for 20 ms. Increase the _delay_ms(20) value to 40 for worn switches.
Avrdude says the device signature is 0x000000Check the USBasp wiring and that the chip has 5 V. On a factory-fresh chip set the USBasp to slow SCK (jumper JP3) for the first fuse write.
Shows 120 and 4 every time after power-upThe settings save 3 seconds after the last button press. Wait a moment before switching off.

Ideas to Extend

  • Add a rotary encoder for faster tempo setting.
  • Drive a small 8 Ω speaker through a transistor for a louder click.
  • Add a 3.5 mm headphone jack with a volume pot for quiet practice.

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

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

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.

ATmega16 Electronic Voting Machine with 16×2 LCD & EEPROM Storage

ATmega16 electronic voting machine on a breadboard with 16x2 LCD, four candidate buttons A to D, enable, result and clear buttons, green and red LEDs and a buzzer

Build an ATmega16 electronic voting machine with four candidate buttons, an officer enable key, a 16×2 LCD result screen and vote counts that survive power cuts in EEPROM.

  • DifficultyIntermediate
  • Build time2–4 hours
  • Board / MCUATmega16 (internal 8 MHz)
  • Parts11 items
  • CodeAVR C

Need it ready-made? Buy Ready Project

This ATmega16 electronic voting machine is a small, self-contained ballot unit for school elections, club polls and classroom demos. Four big buttons stand for candidates A, B, C and D. A presiding officer presses ENABLE before each voter, the voter presses one button, and the vote is counted and saved straight into the chip’s EEPROM.

Because every vote is written to EEPROM the moment it is cast, a power cut or a flat battery never loses the count. The officer can see the totals and the leading candidate on the 16×2 LCD at any time, and can erase all votes only by holding two buttons together for three seconds.

ATmega16 electronic voting machine on a breadboard with 16x2 LCD, four candidate buttons A to D, enable, result and clear buttons, green and red LEDs and a buzzer

How It Works

  • One vote per enable: the candidate buttons are ignored until the officer presses ENABLE. The green LED then lights and the LCD says Cast your vote. After one valid press the machine locks again, so a voter cannot press twice.
  • Clean key reading: the four candidate buttons sit on PB0 to PB3 with the chip’s internal pull-ups. The code debounces each press for 30 ms and rejects two buttons pressed together, so a single press always means a single vote.
  • Power-safe storage: each candidate has a 16-bit counter in EEPROM. eeprom_update_word() writes only when the value changes, which saves wear on the EEPROM cells. A magic byte tells the code whether the EEPROM has been set up yet.
  • Results: RESULT shows all four counts as A:012 B:003 and C:000 D:007, then the leading candidate, or TIE if the top two are level.
  • Protected clear: holding RESULT and CLEAR together for 3 seconds wipes the counts, with a long beep to confirm. Letting go early cancels it.
  • Clock and fuses: the chip runs on its internal 8 MHz oscillator, so no crystal is needed. JTAG is switched off and EESAVE is set, so re-flashing the program keeps the stored votes.

Components Required

  • ATmega16 (40-pin DIP) microcontroller – 1
  • 16×2 character LCD (HD44780) – 1
  • 10 kΩ potentiometer (LCD contrast) – 1
  • Large tactile push buttons for candidates A, B, C, D – 4
  • Small tactile push buttons for ENABLE, RESULT, CLEAR – 3
  • Green LED (ready) and red LED (vote recorded) – 1 each
  • 220 Ω resistors for the LEDs – 2
  • 5V active buzzer – 1
  • 10 kΩ resistor (RESET pull-up) and 100 nF capacitors (decoupling) – 1 + 2
  • USBasp programmer and 5V regulated supply (USB power module or 7805) – 1 each
  • Breadboard or perfboard and jumper wires – 1 set

Wiring Table

Part / pinATmega16 pinNotes
LCD RSPA0 (pin 40)LCD RW to GND
LCD ENPA1 (pin 39)
LCD D4, D5, D6, D7PA4, PA5, PA6, PA7 (pins 36 to 33)4-bit mode, LCD D0 to D3 not connected
LCD V010 kΩ pot wiperPot ends to 5V and GND, sets the contrast
Candidate A, B, C, DPB0, PB1, PB2, PB3 (pins 1 to 4)Other leg of each button to GND
ENABLE buttonPD2 (pin 16)Other leg to GND
RESULT buttonPD3 (pin 17)Other leg to GND
CLEAR buttonPD4 (pin 18)Other leg to GND
Green LED (ready)PD5 (pin 19) through 220 ΩCathode to GND
Red LED (recorded)PD6 (pin 20) through 220 ΩCathode to GND
Active buzzer +PD7 (pin 21)Buzzer – to GND
VCC / AVCCPins 10 and 305V, with a 100 nF capacitor to GND at each
GNDPins 11 and 31Common ground
RESETPin 910 kΩ to 5V, also goes to the USBasp RST line

Connection Diagram

The illustration above shows the build on a breadboard. It is a layout guide only (the crystal shown there is not needed because the code uses the internal 8 MHz clock). Follow the pin-accurate drawing below, which matches the wiring table exactly.

ATmega16 Electronic Voting Machine – Pin-Accurate Wiring Power 5V to VCC (pin 10) and AVCC (pin 30), GND to pins 11 and 31 100 nF from VCC to GND close to the chip 10 kΩ from RESET (pin 9) to 5V 16×2 LCD RS to PA0 (pin 40), EN to PA1 (pin 39), RW to GND D4 to PA4 (36), D5 to PA5 (35), D6 to PA6 (34), D7 to PA7 (33) VSS GND, VDD 5V, V0 to 10 kΩ pot wiper, A to 5V via 220 Ω, K to GND Candidate keys A to PB0 (pin 1), B to PB1 (pin 2) C to PB2 (pin 3), D to PB3 (pin 4) Other leg of each button to GND (internal pull-ups) Officer keys ENABLE to PD2 (pin 16), RESULT to PD3 (pin 17) CLEAR to PD4 (pin 18), other legs to GND LEDs + buzzer Green LED via 220 Ω to PD5 (pin 19), red LED via 220 Ω to PD6 (pin 20) Buzzer + to PD7 (pin 21), – to GND LED cathodes to GND
Pin-accurate connection diagram for the ATmega16 electronic voting machine.

AVR C Code

Save the code as atmega16_voting.c. It was compiled with avr-gcc for the ATmega16 and uses about 1.8 KB of flash. Build and flash it with a USBasp using these commands (Microchip Studio works too):

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

The fuse values select the internal 8 MHz oscillator (lfuse 0xE4), turn off JTAG and keep the EEPROM when you re-flash (hfuse 0xD1). Set the fuses once, before flashing the program.

/*
 * ATmega16 Electronic Voting Machine with 16x2 LCD & 4 Candidate Buttons
 * ardiunoprojecthub.online
 *
 * MCU   : ATmega16 @ 8 MHz internal oscillator
 * Fuses : lfuse=0xE4 (internal 8 MHz), hfuse=0xD1 (JTAG off, EESAVE on)
 *         EESAVE keeps the stored votes when you re-flash the chip.
 *
 * LCD 16x2 (4-bit): RS=PA0, EN=PA1, D4=PA4, D5=PA5, D6=PA6, D7=PA7, RW=GND
 * Candidate buttons: A=PB0, B=PB1, C=PB2, D=PB3   (to GND, internal pull-ups)
 * Officer buttons  : ENABLE=PD2, RESULT=PD3, CLEAR=PD4 (to GND, pull-ups)
 * LEDs             : green READY=PD5, red RECORDED=PD6 (each via 220 ohm)
 * Buzzer (active)  : PD7
 *
 * How to use:
 *   1. Officer presses ENABLE -> green LED, "Cast your vote".
 *   2. Voter presses ONE candidate button -> vote saved in EEPROM, beep,
 *      red LED, machine locks until ENABLE is pressed again.
 *   3. RESULT shows all four counts, then the leader (or a tie).
 *   4. Hold RESULT + CLEAR together for 3 seconds to erase all votes.
 */
#define F_CPU 8000000UL
#include <avr/io.h>
#include <avr/eeprom.h>
#include <util/delay.h>
#include <stdint.h>

#define NUM_CAND 4
#define EE_MAGIC 0x5A

uint8_t  EEMEM ee_magic;
uint16_t EEMEM ee_votes[NUM_CAND];

static uint16_t votes[NUM_CAND];
static const char cand_name[NUM_CAND] = {'A', 'B', 'C', 'D'};

/* ---------------- LCD (HD44780, 4-bit mode on PORTA) ---------------- */
#define LCD_RS PA0
#define LCD_EN PA1

static void lcd_pulse(void) {
    PORTA |= (1 << LCD_EN); _delay_us(1);
    PORTA &= ~(1 << LCD_EN); _delay_us(50);
}
static void lcd_nibble(uint8_t n) {            /* high nibble in bits 7..4 */
    PORTA = (PORTA & 0x0F) | (n & 0xF0);
    lcd_pulse();
}
static void lcd_send(uint8_t v, uint8_t rs) {
    if (rs) PORTA |= (1 << LCD_RS); else PORTA &= ~(1 << LCD_RS);
    lcd_nibble(v);
    lcd_nibble(v << 4);
}
static void lcd_cmd(uint8_t c)  { lcd_send(c, 0); if (c < 4) _delay_ms(2); }
static void lcd_char(char c)    { lcd_send(c, 1); }
static void lcd_print(const char *s) { while (*s) lcd_char(*s++); }
static void lcd_goto(uint8_t col, uint8_t row) { lcd_cmd(0x80 | (row ? 0x40 : 0x00) | col); }

static void lcd_init(void) {
    DDRA |= 0xF3;                       /* PA0, PA1, PA4..PA7 outputs */
    _delay_ms(50);
    PORTA &= ~(1 << LCD_RS);
    lcd_nibble(0x30); _delay_ms(5);     /* HD44780 wake-up sequence */
    lcd_nibble(0x30); _delay_us(150);
    lcd_nibble(0x30);
    lcd_nibble(0x20);                   /* 4-bit mode */
    lcd_cmd(0x28);                      /* 2 lines, 5x8 font */
    lcd_cmd(0x0C);                      /* display on, cursor off */
    lcd_cmd(0x06);                      /* auto-increment */
    lcd_cmd(0x01);
}
static void lcd_two(const char *l1, const char *l2) {
    lcd_cmd(0x01);
    lcd_goto(0, 0); lcd_print(l1);
    lcd_goto(0, 1); lcd_print(l2);
}
static void lcd_num3(uint16_t n) {      /* prints 000..999 */
    if (n > 999) n = 999;
    lcd_char('0' + n / 100);
    lcd_char('0' + (n / 10) % 10);
    lcd_char('0' + n % 10);
}

/* ---------------- buttons, LEDs, buzzer ---------------- */
#define BTN_ENABLE PD2
#define BTN_RESULT PD3
#define BTN_CLEAR  PD4
#define LED_READY  PD5
#define LED_REC    PD6
#define BUZZER     PD7

static uint8_t pressed_d(uint8_t pin) { return !(PIND & (1 << pin)); }

static void beep(uint16_t ms) {
    PORTD |= (1 << BUZZER);
    while (ms--) _delay_ms(1);
    PORTD &= ~(1 << BUZZER);
}

/* Wait until every button is released, then debounce */
static void wait_release(void) {
    while ((PINB & 0x0F) != 0x0F || (PIND & 0x1C) != 0x1C) ;
    _delay_ms(40);
}

/* Returns 0..3 for a candidate button, or 0xFF if none / more than one */
static uint8_t read_candidate(void) {
    uint8_t b = ~PINB & 0x0F;
    if (b == 0) return 0xFF;
    _delay_ms(30);                       /* debounce */
    if ((~PINB & 0x0F) != b) return 0xFF;
    switch (b) {                         /* reject two keys at once */
        case 0x01: return 0;
        case 0x02: return 1;
        case 0x04: return 2;
        case 0x08: return 3;
        default:   return 0xFF;
    }
}

/* ---------------- EEPROM storage ---------------- */
static void votes_load(void) {
    if (eeprom_read_byte(&ee_magic) != EE_MAGIC) {      /* first power-up */
        for (uint8_t i = 0; i < NUM_CAND; i++) eeprom_update_word(&ee_votes[i], 0);
        eeprom_update_byte(&ee_magic, EE_MAGIC);
    }
    for (uint8_t i = 0; i < NUM_CAND; i++) votes[i] = eeprom_read_word(&ee_votes[i]);
}
static void votes_save(uint8_t i) { eeprom_update_word(&ee_votes[i], votes[i]); }

/* ---------------- screens ---------------- */
static void show_idle(void) {
    uint16_t total = 0;
    for (uint8_t i = 0; i < NUM_CAND; i++) total += votes[i];
    lcd_two("Voting Machine", "Total votes:");
    lcd_goto(13, 1); lcd_num3(total);
}

static void show_result(void) {
    lcd_cmd(0x01);
    for (uint8_t i = 0; i < NUM_CAND; i++) {
        lcd_goto((i % 2) ? 8 : 0, i / 2);           /* A B on row 0, C D on row 1 */
        lcd_char(cand_name[i]); lcd_char(':'); lcd_num3(votes[i]);
    }
    _delay_ms(4000);

    uint8_t lead = 0, tie = 0;
    for (uint8_t i = 1; i < NUM_CAND; i++) {
        if (votes[i] > votes[lead]) { lead = i; tie = 0; }
        else if (votes[i] == votes[lead]) tie = 1;
    }
    if (votes[lead] == 0)  lcd_two("No votes yet", "");
    else if (tie)          lcd_two("Result: TIE", "Check counts");
    else {
        lcd_two("Leading:", "Candidate ");
        lcd_goto(10, 1); lcd_char(cand_name[lead]);
        lcd_goto(9, 0); lcd_num3(votes[lead]); lcd_print(" vt");
    }
    _delay_ms(3000);
}

static void try_clear(void) {
    lcd_two("Hold 3 s to", "clear all votes");
    for (uint8_t t = 0; t < 30; t++) {               /* 30 x 100 ms = 3 s */
        if (!(pressed_d(BTN_RESULT) && pressed_d(BTN_CLEAR))) { show_idle(); return; }
        _delay_ms(100);
    }
    for (uint8_t i = 0; i < NUM_CAND; i++) { votes[i] = 0; votes_save(i); }
    beep(600);
    lcd_two("All votes", "cleared");
    _delay_ms(1500);
    wait_release();
    show_idle();
}

int main(void) {
    /* JTAG off in code as well (write JTD twice within 4 cycles) */
    MCUCSR |= (1 << JTD); MCUCSR |= (1 << JTD);

    DDRB  &= 0xF0;  PORTB |= 0x0F;                    /* candidate buttons */
    DDRD  |= (1 << LED_READY) | (1 << LED_REC) | (1 << BUZZER);
    DDRD  &= ~((1 << BTN_ENABLE) | (1 << BTN_RESULT) | (1 << BTN_CLEAR));
    PORTD |= (1 << BTN_ENABLE) | (1 << BTN_RESULT) | (1 << BTN_CLEAR);

    lcd_init();
    votes_load();
    beep(100);
    show_idle();

    while (1) {
        if (pressed_d(BTN_RESULT) && pressed_d(BTN_CLEAR)) { try_clear(); continue; }

        if (pressed_d(BTN_RESULT)) {
            _delay_ms(30);
            if (pressed_d(BTN_CLEAR)) continue;        /* user is going for clear */
            wait_release();
            show_result();
            show_idle();
        }

        if (pressed_d(BTN_ENABLE)) {
            wait_release();
            PORTD |= (1 << LED_READY);
            PORTD &= ~(1 << LED_REC);
            lcd_two("Cast your vote", "Press A B C or D");
            beep(80);

            uint8_t c;
            while ((c = read_candidate()) == 0xFF) ;     /* one vote only */
            votes[c]++;
            votes_save(c);                               /* safe on power cut */

            PORTD &= ~(1 << LED_READY);
            PORTD |= (1 << LED_REC);
            lcd_two("Vote recorded", "Thank you!");
            beep(400);
            wait_release();                              /* ignore extra presses */
            _delay_ms(1500);
            PORTD &= ~(1 << LED_REC);
            show_idle();
        }
    }
}

Setting Up and Testing

  • Power the board. You should hear a short beep and see Voting Machine and the total vote count. If the LCD shows only blocks, turn the contrast pot.
  • Press ENABLE. The green LED lights and the LCD asks for a vote.
  • Press candidate B. The red LED lights, the buzzer beeps and the LCD says Vote recorded. Pressing B again does nothing until ENABLE is pressed.
  • Cast a few more votes, then press RESULT to see the four counts and the leader.
  • Unplug the power, plug it back in and press RESULT. The counts are still there.
  • Hold RESULT and CLEAR for 3 seconds to reset everything before a real election.

Tip: mount the four candidate buttons on a separate panel for the voter and keep ENABLE, RESULT and CLEAR on the officer’s side, joined by a short ribbon cable.

Troubleshooting

ProblemFix
LCD is blank or shows a row of blocksAdjust the 10 kΩ contrast pot and check RW is tied to GND and D4 to D7 go to PA4 to PA7.
Everything is very slow and the LCD shows junkThe chip is still on its 1 MHz factory clock. Write lfuse 0xE4 with avrdude.
Counts reset after re-flashingEESAVE is off. Use hfuse 0xD1, then the EEPROM is kept when you upload new code.
A vote is counted twiceA button is bouncing badly. Raise the 30 ms debounce in read_candidate() to 60 ms or swap the button.
Nothing happens after pressing ENABLECheck the ENABLE button goes to PD2 and GND, using legs on opposite sides of the button.
Counts look like 999 or random numbers on first power-upHold RESULT and CLEAR for 3 seconds once to zero the EEPROM.

Ideas to Extend

  • Add more candidates on PB4 to PB7 and show the names on the LCD instead of letters.
  • Send the final result to a PC or phone through an HC-05 Bluetooth module on the UART pins.
  • Add a 4×4 keypad officer PIN so only the officer can see results or clear the votes.

ATmega16 Mini Piano with 8 Keys, Buzzer & Demo Song

ATmega16 mini piano on a breadboard with 8 push button keys, 8 LEDs, octave and song buttons, passive buzzer and USBasp programmer

Build an ATmega16 mini piano with 8 push-button keys, a passive buzzer, one LED per key, an octave switch and a built-in demo song, all in plain AVR C.

  • DifficultyEasy
  • Build time1–2 hours
  • Board / MCUATmega16 (internal 8 MHz)
  • Parts10 items
  • CodeAVR C

Need it ready-made? Buy Ready Project

This ATmega16 mini piano turns eight push buttons into a one-octave keyboard. Press a key and a passive buzzer plays its note (C, D, E, F, G, A, B and high C) while the matching LED lights up. An OCTAVE button shifts all keys one octave higher, and a SONG button plays a short demo tune with the LEDs following the music.

It is a small, fun first project for the ATmega16. It needs no crystal, no LCD and no libraries, and it teaches three useful things: reading buttons with internal pull-ups, making sound with Timer1 in CTC mode, and storing tables in flash with PROGMEM. The whole program is only about 850 bytes.

ATmega16 mini piano on a breadboard with 8 push button keys, 8 LEDs, octave and song buttons, passive buzzer and USBasp programmer

How It Works

  • Keys: the eight buttons sit on PORTA (PA0 to PA7). Each pin uses the chip’s internal pull-up, so it reads 1 when the key is up and 0 when it is pressed. No external resistors are needed.
  • Making the sound: Timer1 runs in CTC mode and toggles the OC1A pin (PD5) every time it reaches the value in OCR1A. This gives a clean square wave at f = 8 MHz / (16 × (1 + OCR1A)). For middle C (262 Hz) OCR1A is 1907. The timer does the work in hardware, so the CPU is free to keep scanning the keys.
  • Which note wins: if you press two keys at once, the lowest key plays. The note stops as soon as you let go, and the buzzer pin is pulled low so no current flows through it while silent.
  • Octave button: PD2 toggles between the low octave (C4 to C5) and the high octave (C5 to C6) by doubling every frequency. The blue LED on PD6 shows that the high octave is on.
  • Demo song: PD3 plays the first lines of “Twinkle Twinkle Little Star”. The notes and their lengths are stored in flash with PROGMEM. Press SONG again to stop it early.
  • Key LEDs: PORTC lights one LED for the note that is playing. PC2 to PC5 are also the JTAG pins, so JTAG is turned off with the fuse and again in code.

Components Required

  • ATmega16 or ATmega16A microcontroller (40-pin DIP) – 1
  • Tactile push buttons, 12 mm – 10 (8 keys, OCTAVE and SONG)
  • Passive buzzer, 5V (the type without a built-in oscillator) – 1
  • 5 mm LEDs – 9 (8 red for the keys, 1 blue for the octave)
  • 220 Ω resistors – 9
  • 10 kΩ resistor (RESET pull-up) – 1
  • 100 nF ceramic capacitors – 2
  • 5V regulated supply (breadboard power module or USB 5V) – 1
  • USBasp programmer with 10-pin to 6-pin ISP cable – 1
  • Full-size breadboard and jumper wires

Wiring Table

Part / signalATmega16 pinNotes
5V supplyVCC (pin 10) and AVCC (pin 30)100 nF capacitor across each pair
GNDPins 11 and 31
10 kΩ pull-upRESET (pin 9) to 5VKeeps the chip running
Key CPA0 (pin 40)Button to GND
Key DPA1 (pin 39)Button to GND
Key EPA2 (pin 38)Button to GND
Key FPA3 (pin 37)Button to GND
Key GPA4 (pin 36)Button to GND
Key APA5 (pin 35)Button to GND
Key BPA6 (pin 34)Button to GND
Key C’ (high C)PA7 (pin 33)Button to GND
Key LEDs 1 to 8PC0 to PC7 (pins 22 to 29)Each through 220 Ω, cathode to GND
OCTAVE buttonPD2 (pin 16)Other leg to GND
SONG buttonPD3 (pin 17)Other leg to GND
Passive buzzer (+)PD5 / OC1A (pin 19)Buzzer (-) to GND
Octave LEDPD6 (pin 20)Through 220 Ω, cathode to GND
USBasp MOSI / MISO / SCKPB5 / PB6 / PB7 (pins 6, 7, 8)Only for programming
USBasp RSTRESET (pin 9)

Connection Diagram

The illustration above shows how the parts sit on the breadboard. It is a placement guide only, and its wire colours and labels are not exact. The pin-accurate drawing below matches the wiring table, so follow it while you build.

ATmega16 Mini Piano – Pin-Accurate Wiring Power 5V to VCC (pin 10) and AVCC (pin 30) GND to pins 11 and 31 100 nF from pin 10 to 11 and from pin 30 to 31 10 kΩ from RESET (pin 9) to 5V 8 piano keys C PA0 (40), D PA1 (39), E PA2 (38), F PA3 (37) G PA4 (36), A PA5 (35), B PA6 (34), C’ PA7 (33) Other leg of every key button to GND (internal pull-ups) 8 key LEDs PC0 to PC7 (pins 22 to 29), one LED per key Each pin: 220 Ω to LED anode, cathode to GND JTAG fuse off (hfuse 0xD9) so PC2 to PC5 work Extra buttons OCTAVE button: PD2 (pin 16) to GND SONG button: PD3 (pin 17) to GND Buzzer and octave LED Passive buzzer (+) to PD5 / OC1A (pin 19), (-) to GND Octave LED: PD6 (pin 20), 220 Ω, LED, GND ISP (USBasp) MOSI PB5 (6), MISO PB6 (7), SCK PB7 (8) RST to pin 9, VCC 5V, GND GND
Pin-accurate connection diagram for the ATmega16 mini piano.

AVR C Code

Save the code as atmega16_piano.c. It was compiled with avr-gcc for the ATmega16 and uses about 850 bytes of flash. Build and flash it with a USBasp using these commands (Microchip Studio works too):

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

The fuse values select the internal 8 MHz oscillator (lfuse 0xE4) and turn off JTAG (hfuse 0xD9) so all of PORTC can drive the LEDs. Set the fuses once, before flashing the program.

/*
 * ATmega16 Mini Piano with 8 Keys, Octave Button, Demo Song and Passive Buzzer
 * ardiunoprojecthub.online - Project #48
 *
 * MCU   : ATmega16 / ATmega16A, internal 8 MHz RC oscillator
 * Fuses : lfuse 0xE4 (internal 8 MHz), hfuse 0xD9 (JTAG off)
 *
 * Keys  : PA0..PA7 = C D E F G A B C' (push buttons to GND, internal pull-ups)
 * LEDs  : PC0..PC7 = one LED per key (220R to GND)
 * OCTAVE button : PD2 to GND (toggles low / high octave)
 * SONG button   : PD3 to GND (plays a short demo tune)
 * Octave LED    : PD6 (220R to GND), ON in high octave
 * Buzzer        : PD5 / OC1A -> passive buzzer (+), buzzer (-) to GND
 *
 * Sound: Timer1 in CTC mode toggles OC1A in hardware, so the tone is a clean
 * square wave and the CPU is free to scan the keys.
 *   f = F_CPU / (2 * 8 * (1 + OCR1A))   (prescaler 8)
 */
#define F_CPU 8000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <avr/pgmspace.h>

/* Low octave note frequencies in Hz: C4 D4 E4 F4 G4 A4 B4 C5 */
static const uint16_t note_hz[8] PROGMEM = {262, 294, 330, 349, 392, 440, 494, 523};

static uint8_t high_octave = 0;   /* 0 = C4..C5, 1 = C5..C6 */

/* Start a tone of 'hz' on OC1A (PD5). hz = 0 stops the sound. */
static void tone_on(uint16_t hz)
{
    if (hz == 0) {
        TCCR1A = 0;                 /* disconnect OC1A */
        TCCR1B = 0;                 /* stop timer */
        PORTD &= ~(1 << PD5);       /* buzzer pin low (no DC through buzzer) */
        return;
    }
    uint16_t top = (uint16_t)(F_CPU / (16UL * hz)) - 1;
    OCR1A  = top;
    TCNT1  = 0;
    TCCR1A = (1 << COM1A0);               /* toggle OC1A on compare match */
    TCCR1B = (1 << WGM12) | (1 << CS11);  /* CTC mode, prescaler 8 */
}

static uint16_t key_freq(uint8_t key)
{
    uint16_t f = pgm_read_word(&note_hz[key]);
    return high_octave ? (f * 2) : f;
}

/* Wait in 10 ms steps so the delay can be any length */
static void wait_ms(uint16_t ms)
{
    while (ms >= 10) { _delay_ms(10); ms -= 10; }
}

/* Demo tune: "Twinkle Twinkle Little Star" (first two lines).
 * Each entry is a key index 0..7; 0xFF = end. Durations in ms. */
static const uint8_t song_notes[] PROGMEM = {
    0,0,4,4,5,5,4,  3,3,2,2,1,1,0,
    4,4,3,3,2,2,1,  4,4,3,3,2,2,1, 0xFF
};
static const uint8_t song_len[] PROGMEM = {   /* x10 ms */
    40,40,40,40,40,40,80, 40,40,40,40,40,40,80,
    40,40,40,40,40,40,80, 40,40,40,40,40,40,80
};

static void play_song(void)
{
    for (uint8_t i = 0; ; i++) {
        uint8_t k = pgm_read_byte(&song_notes[i]);
        if (k == 0xFF) break;
        uint16_t len = pgm_read_byte(&song_len[i]) * 10;
        PORTC = (1 << k);              /* light the LED of the key being played */
        tone_on(key_freq(k));
        wait_ms(len - 50);
        tone_on(0);                    /* short gap between notes */
        PORTC = 0;
        wait_ms(50);
        /* Press SONG again to stop the tune early */
        if (!(PIND & (1 << PD3)) && i > 2) {
            while (!(PIND & (1 << PD3))) ;   /* wait for release */
            _delay_ms(30);
            break;
        }
    }
}

int main(void)
{
    /* JTAG uses PC2..PC5. Disable it in code too (write JTD twice within 4 cycles),
       in case the JTAGEN fuse is still programmed. */
    MCUCSR |= (1 << JTD);
    MCUCSR |= (1 << JTD);

    DDRA  = 0x00; PORTA = 0xFF;                /* 8 keys: inputs with pull-ups */
    DDRC  = 0xFF; PORTC = 0x00;                /* 8 key LEDs: outputs, off */
    DDRD  = (1 << PD5) | (1 << PD6);           /* buzzer and octave LED outputs */
    PORTD = (1 << PD2) | (1 << PD3);           /* pull-ups on OCTAVE and SONG buttons */

    /* Start-up chirp so you know it is alive */
    tone_on(1047); _delay_ms(80); tone_on(0);

    uint8_t last_key = 0xFF;

    while (1) {
        /* ---- OCTAVE button (toggle on press) ---- */
        if (!(PIND & (1 << PD2))) {
            _delay_ms(25);                         /* debounce */
            if (!(PIND & (1 << PD2))) {
                high_octave ^= 1;
                if (high_octave) PORTD |= (1 << PD6); else PORTD &= ~(1 << PD6);
                last_key = 0xFF;                   /* re-start any held note */
                while (!(PIND & (1 << PD2))) ;     /* wait for release */
                _delay_ms(25);
            }
        }

        /* ---- SONG button ---- */
        if (!(PIND & (1 << PD3))) {
            _delay_ms(25);
            if (!(PIND & (1 << PD3))) {
                while (!(PIND & (1 << PD3))) ;
                _delay_ms(25);
                play_song();
                last_key = 0xFF;
            }
        }

        /* ---- Piano keys: the lowest pressed key wins ---- */
        uint8_t pressed = ~PINA;                   /* 1 = key pressed */
        uint8_t key = 0xFF;
        for (uint8_t i = 0; i < 8; i++) {
            if (pressed & (1 << i)) { key = i; break; }
        }

        if (key != last_key) {
            _delay_ms(5);                          /* small debounce on change */
            if (key == 0xFF) {
                tone_on(0);
                PORTC = 0x00;
            } else {
                tone_on(key_freq(key));
                PORTC = (1 << key);
            }
            last_key = key;
        }
    }
}

Testing

  • Power on. You should hear a short high chirp, which means the chip is running at 8 MHz.
  • Press each key from C to high C. You should hear a rising scale and see the LEDs light one by one.
  • Press OCTAVE. The blue LED comes on and every key now plays one octave higher. Press it again to go back.
  • Press SONG to hear the demo tune. Press SONG again to stop it early.

Troubleshooting

ProblemFix
No sound at allMake sure the buzzer is a passive type. An active buzzer only beeps at its own fixed pitch. Check the buzzer is on PD5 (pin 19), not PD6.
Notes sound too low and slowThe chip is still on its 1 MHz factory setting. Write lfuse 0xE4 with avrdude so it runs at 8 MHz.
LEDs on PC2 to PC5 never lightJTAG is still on. Write hfuse 0xD9. The code also disables JTAG at start-up.
A note plays without pressing anythingA key wire is touching 5V or a button is fitted the wrong way round. Turn the button 90 degrees so its legs bridge the breadboard gap correctly.
avrdude says “target doesn’t answer”Check the six ISP wires and the 10 kΩ on RESET. Use the USBasp slow-clock jumper (or -B 10) on a new chip.
Sound is very quietSmall passive buzzers are quiet. Use an 8 Ω speaker through a BC547 transistor and a 100 Ω base resistor for more volume.

Ideas to Extend

  • Add a 16×2 LCD that shows the note name and the octave.
  • Add a record button that saves your tune in EEPROM and plays it back.
  • Use a second timer to play two notes at once on two buzzers.

ATmega16 Digital Clock with DS1307 RTC, DHT11, Alarm & Relay Timer

ATmega16 digital clock wiring with DS1307 RTC, DHT11 sensor, 16x2 LCD, buttons, buzzer and relay module

Build an ATmega16 digital clock with a DS1307 RTC, DHT11 temperature and humidity sensor, 16×2 LCD, buzzer alarm and relay timer. Wiring table, diagram and full AVR C code.

  • DifficultyAdvanced
  • Build time5–8 hours
  • Board / MCUATmega16
  • Parts11 items
  • CodeAVR C

Need it ready-made? Buy Ready Project

This ATmega16 digital clock combines a DS1307 real-time clock, a DHT11 temperature and humidity sensor, a 16×2 LCD, a buzzer alarm and a relay timer in one build. It keeps accurate time even when the power goes off, shows the date, room temperature and humidity, wakes you with an alarm, and switches a lamp or appliance on and off at set hours every day.

Everything is written in plain AVR C with no libraries, so it is a great project to learn I2C (TWI), single-wire sensor timing, LCD driving and EEPROM storage on the ATmega16.

ATmega16 digital clock wiring with DS1307 RTC, DHT11 sensor, 16x2 LCD, buttons, buzzer and relay module

How It Works

  • Timekeeping: the DS1307 counts seconds, minutes, hours, date, month and year by itself using its own 32.768 kHz crystal. A CR2032 coin cell keeps it running during power cuts. The ATmega16 reads it over I2C (TWI) at 100 kHz and converts the BCD values to normal numbers.
  • Temperature and humidity: every 5 seconds the microcontroller sends an 18 ms start pulse to the DHT11 and reads its 40-bit reply, checking the checksum before showing the values.
  • Display: line 1 shows HH:MM:SS and the date, line 2 shows temperature, humidity and an AL mark when the alarm is armed. The LCD runs in 4-bit mode on PORTA.
  • Alarm: when the time matches the alarm hour and minute, the buzzer beeps for up to 60 seconds. Press any button to stop it.
  • Relay timer: the relay is ON between the ‘Relay ON hour’ and ‘Relay OFF hour’ (it also works across midnight, for example 18 to 6). Set both to the same hour to keep it off. Use it for a porch light, aquarium light or a fan.
  • Settings: press SET to step through hour, minute, day, month, year, alarm hour, alarm minute, alarm on/off, relay ON hour and relay OFF hour. UP and DOWN change the value. The time is written to the DS1307 and the alarm and relay settings are saved in EEPROM, so nothing is lost after a reset.

Components Required

  • ATmega16 (or ATmega16A) microcontroller, 40-pin DIP – 1
  • 16 MHz crystal – 1, with 22pF ceramic capacitors – 2
  • DS1307 RTC module with CR2032 coin cell (Tiny RTC) – 1
  • DHT11 temperature and humidity sensor – 1
  • 16×2 LCD (HD44780) – 1, with 10k potentiometer for contrast – 1
  • Tactile push buttons – 3 (SET, UP, DOWN)
  • Active 5V buzzer – 1
  • 5V single-channel relay module – 1
  • 7805 voltage regulator – 1, with 10uF and 0.1uF capacitors
  • 10k resistors – 2 (RESET pull-up, DHT11 pull-up), 220 ohm resistor – 1 (LCD backlight)
  • USBasp programmer, breadboard or PCB, jumper wires, 9-12V DC adapter

Wiring Table

Component pinATmega16 pinNotes
7805 OUT (5V)VCC (10), AVCC (30)Add 0.1uF near the chip
GNDGND (11, 31)Common ground for all modules
10k resistorRESET (9) to 5VAlso goes to the USBasp RESET
16 MHz crystalXTAL1 (13), XTAL2 (12)22pF from each leg to GND
LCD RSPA0 (40)
LCD ENPA1 (39)
LCD D4 / D5 / D6 / D7PA4 / PA5 / PA6 / PA7 (36 / 35 / 34 / 33)4-bit mode
LCD RWGNDWrite only
LCD V010k pot wiperPot ends to 5V and GND
DS1307 SCLPC0 (22)4.7k pull-up to 5V
DS1307 SDAPC1 (23)4.7k pull-up to 5V
DHT11 DATAPD4 (18)10k pull-up to 5V
SET buttonPB0 (1)Other leg to GND
UP buttonPB1 (2)Other leg to GND
DOWN buttonPB2 (3)Other leg to GND
Buzzer +PD6 (20)Buzzer – to GND
Relay module INPD7 (21)Relay VCC to 5V, GND to GND

Connection Diagram

The illustration above shows the general layout; its wire routes are only for orientation. The pin-accurate drawing below matches the wiring table exactly, so follow it while building.

ATmega16 RTC Clock – Pin-Accurate Wiring Power (7805) 9-12V DC in to 7805 IN, 7805 OUT gives regulated 5V 5V to VCC (pin 10) and AVCC (pin 30); GND to pins 11 and 31 0.1uF across VCC-GND, 10k from RESET (pin 9) to 5V Clock (16 MHz) Crystal between XTAL1 (pin 13) and XTAL2 (pin 12) 22pF from each crystal leg to GND 16×2 LCD RS to PA0 (pin 40), EN to PA1 (pin 39), RW to GND D4-D7 to PA4-PA7 (pins 36, 35, 34, 33) VSS GND, VDD 5V, V0 to 10k pot wiper, A 5V via 220R, K GND DS1307 RTC SCL to PC0 (pin 22), SDA to PC1 (pin 23) 4.7k pull-ups to 5V on SDA and SCL (most modules have them) VCC 5V, GND GND, CR2032 backup cell fitted DHT11 DATA to PD4 (pin 18) with 10k pull-up to 5V VCC 5V, GND GND Buttons SET to PB0 (pin 1), UP to PB1 (pin 2), DOWN to PB2 (pin 3) Other leg of each button to GND (internal pull-ups) Buzzer and relay Active buzzer + to PD6 (pin 20), – to GND Relay module IN to PD7 (pin 21), VCC 5V, GND GND
Pin-accurate connection diagram for the ATmega16 RTC clock with DHT11, alarm and relay.

Code

The firmware is plain AVR C (about 4.5 KB of flash). Compile it with Microchip Studio or avr-gcc, then flash it with a USBasp. Set the fuses for the external 16 MHz crystal and JTAG off: avrdude -c usbasp -p m16 -U lfuse:w:0xFF:m -U hfuse:w:0xD9:m. Then upload with avr-gcc -mmcu=atmega16 -Os -o clock.elf rtc_clock.c, avr-objcopy -O ihex clock.elf clock.hex and avrdude -c usbasp -p m16 -U flash:w:clock.hex.

/*
 * ATmega16 Digital Clock with DS1307 RTC, DHT11, Alarm & Relay Timer
 * ardiunoprojecthub.online
 *
 * MCU   : ATmega16 @ 16 MHz external crystal
 * Fuses : lfuse=0xFF (ext. crystal), hfuse=0xD9 (JTAG off)
 *
 * LCD 16x2 (4-bit): RS=PA0, EN=PA1, D4=PA4, D5=PA5, D6=PA6, D7=PA7, RW=GND
 * DS1307 RTC (I2C): SCL=PC0, SDA=PC1 (4.7k pull-ups to 5V), 3V CR2032 backup
 * DHT11           : DATA=PD4 (10k pull-up to 5V)
 * Buttons (to GND): SET=PB0, UP=PB1, DOWN=PB2 (internal pull-ups)
 * Buzzer (active) : PD6 (through a BC547 if it draws more than 20 mA)
 * Relay module    : IN=PD7 (active HIGH; switch a lamp or appliance)
 *
 * Screen:  line 1 = HH:MM:SS  DD/MM
 *          line 2 = temperature, humidity and alarm flag
 * Press SET to walk through: hour, minute, day, month, year,
 *   alarm hour, alarm minute, alarm on/off, relay ON hour, relay OFF hour.
 * UP / DOWN change the blinking value. After the last item the time is
 * written to the DS1307 and the settings are saved in EEPROM.
 * While the alarm rings, press any button to stop it (auto-stop after 60 s).
 */
#define F_CPU 16000000UL
#include <avr/io.h>
#include <avr/eeprom.h>
#include <util/delay.h>
#include <stdio.h>

/* ---------------- LCD (HD44780, 4-bit mode on PORTA) ---------------- */
#define LCD_RS PA0
#define LCD_EN PA1
static void lcd_pulse(void) { PORTA |= (1 << LCD_EN); _delay_us(1); PORTA &= ~(1 << LCD_EN); _delay_us(50); }
static void lcd_nibble(uint8_t n) { PORTA = (PORTA & 0x0F) | (n & 0xF0); lcd_pulse(); }
static void lcd_send(uint8_t v, uint8_t rs) {
    if (rs) PORTA |= (1 << LCD_RS); else PORTA &= ~(1 << LCD_RS);
    lcd_nibble(v); lcd_nibble(v << 4);
}
static void lcd_cmd(uint8_t c) { lcd_send(c, 0); if (c < 4) _delay_ms(2); }
static void lcd_print(const char *s) { while (*s) lcd_send(*s++, 1); }
static void lcd_goto(uint8_t col, uint8_t row) { lcd_cmd(0x80 | (row ? 0x40 : 0x00) | col); }
static void lcd_init(void) {
    DDRA |= 0xF3;
    _delay_ms(50);
    PORTA &= ~(1 << LCD_RS);
    lcd_nibble(0x30); _delay_ms(5);
    lcd_nibble(0x30); _delay_us(150);
    lcd_nibble(0x30);
    lcd_nibble(0x20);                 /* 4-bit mode */
    lcd_cmd(0x28); lcd_cmd(0x0C); lcd_cmd(0x06); lcd_cmd(0x01);
}

/* ---------------- I2C (TWI) master at 100 kHz ---------------- */
static void i2c_init(void) { TWSR = 0; TWBR = 72; }   /* 16 MHz / (16 + 2*72) = 100 kHz */
static void i2c_wait(void) { uint16_t t = 0xFFFF; while (!(TWCR & (1 << TWINT)) && --t); }
static void i2c_start(void) { TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN); i2c_wait(); }
static void i2c_stop(void)  { TWCR = (1 << TWINT) | (1 << TWSTO) | (1 << TWEN); _delay_us(10); }
static void i2c_write(uint8_t d) { TWDR = d; TWCR = (1 << TWINT) | (1 << TWEN); i2c_wait(); }
static uint8_t i2c_read(uint8_t ack) {
    TWCR = (1 << TWINT) | (1 << TWEN) | (ack ? (1 << TWEA) : 0); i2c_wait(); return TWDR;
}

/* ---------------- DS1307 ---------------- */
#define DS1307 0xD0
static uint8_t bcd2dec(uint8_t b) { return (b >> 4) * 10 + (b & 0x0F); }
static uint8_t dec2bcd(uint8_t d) { return ((d / 10) << 4) | (d % 10); }

typedef struct { uint8_t sec, min, hour, day, month, year; } rtc_t;

static void rtc_read(rtc_t *t) {
    i2c_start(); i2c_write(DS1307); i2c_write(0x00);
    i2c_start(); i2c_write(DS1307 | 1);
    t->sec   = bcd2dec(i2c_read(1) & 0x7F);
    t->min   = bcd2dec(i2c_read(1));
    t->hour  = bcd2dec(i2c_read(1) & 0x3F);   /* 24-hour mode */
    i2c_read(1);                               /* day of week, unused */
    t->day   = bcd2dec(i2c_read(1));
    t->month = bcd2dec(i2c_read(1));
    t->year  = bcd2dec(i2c_read(0));
    i2c_stop();
}
static void rtc_write(const rtc_t *t) {
    i2c_start(); i2c_write(DS1307); i2c_write(0x00);
    i2c_write(dec2bcd(t->sec) & 0x7F);         /* CH bit = 0 keeps the oscillator running */
    i2c_write(dec2bcd(t->min));
    i2c_write(dec2bcd(t->hour));               /* bit 6 = 0 -> 24-hour mode */
    i2c_write(1);
    i2c_write(dec2bcd(t->day));
    i2c_write(dec2bcd(t->month));
    i2c_write(dec2bcd(t->year));
    i2c_stop();
}

/* ---------------- DHT11 on PD4 ---------------- */
#define DHT_PIN PD4
static uint8_t dht_read(uint8_t *temp, uint8_t *hum) {
    uint8_t d[5] = {0};
    DDRD |= (1 << DHT_PIN); PORTD &= ~(1 << DHT_PIN);
    _delay_ms(20);                              /* start signal: 18 ms low */
    PORTD |= (1 << DHT_PIN); _delay_us(30);
    DDRD &= ~(1 << DHT_PIN);                    /* release; external pull-up */
    uint16_t t;
    t = 0; while (PIND & (1 << DHT_PIN))    { if (++t > 200) return 0; _delay_us(1); }
    t = 0; while (!(PIND & (1 << DHT_PIN))) { if (++t > 200) return 0; _delay_us(1); }
    t = 0; while (PIND & (1 << DHT_PIN))    { if (++t > 200) return 0; _delay_us(1); }
    for (uint8_t i = 0; i < 40; i++) {
        t = 0; while (!(PIND & (1 << DHT_PIN))) { if (++t > 200) return 0; _delay_us(1); }
        _delay_us(35);                          /* 26 us high = 0, 70 us high = 1 */
        if (PIND & (1 << DHT_PIN)) d[i / 8] |= (1 << (7 - (i % 8)));
        t = 0; while (PIND & (1 << DHT_PIN))    { if (++t > 200) return 0; _delay_us(1); }
    }
    if ((uint8_t)(d[0] + d[1] + d[2] + d[3]) != d[4]) return 0;  /* checksum */
    *hum = d[0]; *temp = d[2];
    return 1;
}

/* ---------------- Buttons, buzzer, relay ---------------- */
#define BTN_SET  PB0
#define BTN_UP   PB1
#define BTN_DOWN PB2
#define BUZZER   PD6
#define RELAY    PD7

static uint8_t pressed(uint8_t pin) {
    if (!(PINB & (1 << pin))) {
        _delay_ms(25);
        if (!(PINB & (1 << pin))) {
            uint16_t hold = 0;
            while (!(PINB & (1 << pin)) && hold < 300) { _delay_ms(1); hold++; }  /* auto-repeat when held */
            return 1;
        }
    }
    return 0;
}

/* ---------------- Settings in EEPROM ---------------- */
typedef struct { uint8_t magic, al_hour, al_min, al_on, rl_on, rl_off; } cfg_t;
cfg_t EEMEM ee_cfg;
static cfg_t cfg;

static void cfg_load(void) {
    eeprom_read_block(&cfg, &ee_cfg, sizeof cfg);
    if (cfg.magic != 0x5A || cfg.al_hour > 23 || cfg.al_min > 59 || cfg.rl_on > 23 || cfg.rl_off > 23) {
        cfg = (cfg_t){0x5A, 6, 30, 0, 18, 23};   /* defaults: alarm 06:30 off, relay 18:00-23:00 */
        eeprom_update_block(&cfg, &ee_cfg, sizeof cfg);
    }
}

/* Relay is ON between rl_on and rl_off (works across midnight). Same hours = always off. */
static uint8_t relay_should_be_on(uint8_t h) {
    if (cfg.rl_on == cfg.rl_off) return 0;
    if (cfg.rl_on < cfg.rl_off) return h >= cfg.rl_on && h < cfg.rl_off;
    return h >= cfg.rl_on || h < cfg.rl_off;
}

static uint8_t days_in_month(uint8_t m, uint8_t y) {
    static const uint8_t dm[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
    if (m == 2 && (y % 4) == 0) return 29;
    return dm[(m - 1) % 12];
}

/* ---------------- Setting menu ---------------- */
static const char *const labels[10] = {
    "Set Hour", "Set Minute", "Set Day", "Set Month", "Set Year",
    "Alarm Hour", "Alarm Minute", "Alarm On/Off", "Relay ON hour", "Relay OFF hour"
};

static void setup_menu(rtc_t *t) {
    uint8_t *val[10] = {&t->hour, &t->min, &t->day, &t->month, &t->year,
                        &cfg.al_hour, &cfg.al_min, &cfg.al_on, &cfg.rl_on, &cfg.rl_off};
    char buf[17];
    for (uint8_t i = 0; i < 10; i++) {
        lcd_cmd(0x01);
        lcd_goto(0, 0); lcd_print(labels[i]);
        for (;;) {
            uint8_t lo = 0, hi;
            switch (i) {
                case 0: case 5: case 8: case 9: hi = 23; break;
                case 1: case 6: hi = 59; break;
                case 2: lo = 1; hi = days_in_month(t->month, t->year); break;
                case 3: lo = 1; hi = 12; break;
                case 4: hi = 99; break;
                default: hi = 1; break;
            }
            if (*val[i] < lo || *val[i] > hi) *val[i] = lo;
            if (i == 7) snprintf(buf, sizeof buf, "> %-3s           ", cfg.al_on ? "ON" : "OFF");
            else        snprintf(buf, sizeof buf, "> %02u           ", *val[i]);
            lcd_goto(0, 1); lcd_print(buf);
            if (pressed(BTN_UP))   { *val[i] = (*val[i] >= hi) ? lo : *val[i] + 1; }
            if (pressed(BTN_DOWN)) { *val[i] = (*val[i] <= lo) ? hi : *val[i] - 1; }
            if (pressed(BTN_SET))  { while (!(PINB & (1 << BTN_SET))); break; }
            _delay_ms(30);
        }
    }
    t->sec = 0;
    rtc_write(t);
    eeprom_update_block(&cfg, &ee_cfg, sizeof cfg);
    lcd_cmd(0x01); lcd_goto(0, 0); lcd_print("Saved!"); _delay_ms(800); lcd_cmd(0x01);
}

int main(void) {
    MCUCSR |= (1 << JTD); MCUCSR |= (1 << JTD);   /* disable JTAG (write twice) */

    DDRB  &= ~((1 << BTN_SET) | (1 << BTN_UP) | (1 << BTN_DOWN));
    PORTB |=  (1 << BTN_SET) | (1 << BTN_UP) | (1 << BTN_DOWN);   /* pull-ups */
    DDRD  |=  (1 << BUZZER) | (1 << RELAY);
    PORTD &= ~((1 << BUZZER) | (1 << RELAY));

    lcd_init();
    i2c_init();
    cfg_load();

    lcd_goto(0, 0); lcd_print("ATmega16 Clock");
    lcd_goto(0, 1); lcd_print("RTC + DHT11");
    _delay_ms(1200);
    lcd_cmd(0x01);

    rtc_t now;
    rtc_read(&now);
    if (now.month == 0 || now.month > 12 || now.day == 0) {   /* fresh DS1307: start a sane date */
        now = (rtc_t){0, 0, 12, 1, 1, 26};
        rtc_write(&now);
    }

    uint8_t temp = 0, hum = 0, dht_ok = 0, last_sec = 99, dht_timer = 0;
    uint8_t ringing = 0, ring_secs = 0, rang_this_minute = 0;
    char line[17];

    for (;;) {
        if (!ringing && pressed(BTN_SET)) {
            while (!(PINB & (1 << BTN_SET)));
            rtc_read(&now);
            setup_menu(&now);
            last_sec = 99;
        }

        rtc_read(&now);
        if (now.sec != last_sec) {                 /* once per second */
            last_sec = now.sec;

            if (dht_timer == 0) { dht_ok = dht_read(&temp, &hum); dht_timer = 5; }  /* every 5 s */
            dht_timer--;

            snprintf(line, sizeof line, "%02u:%02u:%02u  %02u/%02u", now.hour, now.min, now.sec, now.day, now.month);
            lcd_goto(0, 0); lcd_print(line);
            if (dht_ok) snprintf(line, sizeof line, "%2uC %2u%%RH  %s", temp, hum, cfg.al_on ? "AL" : "  ");
            else        snprintf(line, sizeof line, "DHT11 error %s ", cfg.al_on ? "AL" : "  ");
            lcd_goto(0, 1); lcd_print(line);

            /* Alarm: start once at the set minute */
            if (cfg.al_on && now.hour == cfg.al_hour && now.min == cfg.al_min) {
                if (!rang_this_minute) { ringing = 1; ring_secs = 0; rang_this_minute = 1; }
            } else rang_this_minute = 0;

            if (ringing && ++ring_secs > 60) ringing = 0;   /* auto stop after 60 s */

            /* Relay timer */
            if (relay_should_be_on(now.hour)) PORTD |= (1 << RELAY); else PORTD &= ~(1 << RELAY);
        }

        if (ringing) {
            PORTD |= (1 << BUZZER); _delay_ms(150); PORTD &= ~(1 << BUZZER); _delay_ms(150);
            if ((PINB & 0x07) != 0x07) {               /* any button pressed */
                ringing = 0;
                while ((PINB & 0x07) != 0x07);         /* wait for release */
                _delay_ms(50);
            }
        } else {
            _delay_ms(50);
        }
    }
}

Using the Clock

  • On the first power-up a fresh DS1307 starts at 12:00, 01/01/26. Press SET and set the real time and date.
  • Arm the alarm in the ‘Alarm On/Off’ step; the AL mark appears on line 2.
  • Set the relay hours, for example ON at 18 and OFF at 23 for an evening lamp.
  • Keep the coin cell in the RTC module so the time survives power cuts.

Safety: if the relay switches 230V AC mains, use a relay module with proper isolation, keep the mains wiring in a closed box, and never touch it while powered.

Troubleshooting

ProblemFix
LCD shows only blocksTurn the contrast pot, then check RS, EN and D4-D7 wiring and that the crystal fuses are set.
Time shows 00:00:00 and does not moveThe DS1307 needs its 4.7k pull-ups and a coin cell; some modules stop without a battery. Set the time once with SET.
Time runs too fast or slow on screenThe DS1307 keeps time, not the ATmega16, so check the RTC’s 32.768 kHz crystal is soldered well.
DHT11 error on line 2Add the 10k pull-up on DATA and check the sensor gets 5V. Wrong timing usually means the 16 MHz fuse is not set.
Buttons or PORTC pins act strangeJTAG is on. Program hfuse 0xD9 (the code also disables JTAG at start-up).

Ideas to Extend

  • Add a second relay for a morning schedule.
  • Add an HC-05 Bluetooth module to set the time from a phone.
  • Use a DS3231 instead of the DS1307 for much better accuracy (same I2C address and registers).
  • Log temperature every hour to the ATmega16 EEPROM and show the daily minimum and maximum.

ATmega16 Keypad Password Door Lock with 16×2 LCD & Servo

ATmega16 keypad password door lock wiring illustration with 4x4 keypad, 16x2 LCD, SG90 servo, buzzer and LEDs on a breadboard

Build an ATmega16 keypad password door lock with a 4×4 keypad, 16×2 LCD and servo latch. The password is saved in EEPROM, can be changed from the keypad, and three wrong tries start a lockout. Wiring table, diagram and full AVR C code.

  • DifficultyIntermediate
  • Build time2–4 hours
  • Board / MCUATmega16
  • Parts11 items
  • CodeAVR C

Need it ready-made? Buy Ready Project

This ATmega16 keypad door lock opens a small servo latch only when the right password is typed on a 4×4 membrane keypad. A 16×2 LCD guides the user, shows a star for every digit, and reports access granted, wrong password or lockout. A green LED and a red LED show the lock state, and a buzzer gives key clicks and alarm beeps.

The password is stored in the ATmega16’s built-in EEPROM, so it survives a power cut, and you can change it from the keypad without reprogramming the chip. After three wrong tries the lock refuses input for 30 seconds. It is a solid medium-level project for learning keypad scanning, a 4-bit LCD driver, hardware PWM for a servo and EEPROM storage in plain AVR C, without any Arduino libraries.

ATmega16 keypad password door lock wiring illustration with 4x4 keypad, 16x2 LCD, SG90 servo, buzzer and LEDs on a breadboard

How It Works

  • Keypad scanning: the four rows (PC0 to PC3) are outputs and the four columns (PC4 to PC7) are inputs with internal pull-ups. The code pulls one row low at a time and reads the columns; a low column means that key is pressed. Each key is debounced and the code waits for release.
  • JTAG disabled: PC2 to PC5 are also JTAG pins on the ATmega16. The program writes the JTD bit twice at start-up so PORTC works as normal I/O, and the fuse setting below turns JTAG off as well.
  • LCD in 4-bit mode: a small HD44780 driver sends each byte as two nibbles on PA4 to PA7, using PA0 as RS and PA1 as EN.
  • Servo latch: Timer1 runs in fast PWM mode 14 with ICR1 = 39999 and a prescaler of 8, giving an exact 50 Hz signal on OC1A (PD5). A 1 ms pulse holds the latch locked and a 2 ms pulse turns it to the open position.
  • Password logic: type digits and press # to enter, * to clear. The right code unlocks for 5 seconds (or until you press D), then the servo locks again automatically. Three wrong codes start a 30 second lockout with a countdown and beeps.
  • Changing the password: press A, type the old password, then a new 4 to 8 digit password twice. It is saved to EEPROM with eeprom_update_block(). The default on first power-up is 1234.

Components Required

  • ATmega16 (or ATmega16A) 40-pin DIP microcontroller – 1
  • 16 MHz crystal and two 22 pF capacitors
  • 10 kΩ resistor (reset pull-up) and 0.1 µF decoupling capacitor
  • 4×4 matrix membrane keypad – 1
  • 16×2 character LCD (HD44780) – 1
  • 10 kΩ potentiometer for LCD contrast – 1
  • SG90 micro servo (or a 5 V solenoid lock with a relay for a real door) – 1
  • 5 V active buzzer – 1
  • 5 mm green and red LEDs with 220 Ω resistors – 1 each, plus 220 Ω for the LCD backlight
  • 5 V 1 A regulated supply (7805 module or USB adapter)
  • USBasp programmer, breadboard and jumper wires

Wiring Table

Component pinATmega16 pinNotes
LCD RSPA0 (pin 40)Register select
LCD ENPA1 (pin 39)Enable
LCD D4 / D5 / D6 / D7PA4 / PA5 / PA6 / PA7 (pins 36 / 35 / 34 / 33)4-bit data
LCD RW, VSS, KGNDWrite-only mode
LCD VDD, A (via 220 Ω)+5 VBacklight through resistor
LCD V010 kΩ pot wiperPot ends to +5 V and GND
Keypad R1 / R2 / R3 / R4PC0 / PC1 / PC2 / PC3 (pins 22 / 23 / 24 / 25)Row outputs
Keypad C1 / C2 / C3 / C4PC4 / PC5 / PC6 / PC7 (pins 26 / 27 / 28 / 29)Column inputs with pull-ups
Servo signal (orange)PD5 / OC1A (pin 19)50 Hz hardware PWM
Servo red / brown+5 V / GNDUse a separate 5 V supply with common GND
Buzzer +PD6 (pin 20)Active buzzer, − to GND
Green LED (via 220 Ω)PD2 (pin 16)Unlocked
Red LED (via 220 Ω)PD3 (pin 17)Locked
VCC, AVCCPins 10, 30+5 V with 0.1 µF to GND
GNDPins 11, 31Common ground
RESETPin 910 kΩ to +5 V
16 MHz crystalPins 12, 13 (XTAL2, XTAL1)22 pF from each pin to GND

Connection Diagram

The illustration above shows the breadboard layout. The pin-accurate drawing below matches the wiring table exactly, so follow it while building.

ATmega16 Keypad Password Door Lock – Pin-Accurate Wiring ATmega16 (power) Pin 10 VCC, pin 30 AVCC: +5 V Pin 11 and pin 31 GND: GND Pin 9 RESET: 10 kΩ to +5 V Pin 12/13 XTAL: 16 MHz crystal, 22 pF to GND each 0.1 µF across VCC and GND 16×2 LCD VSS, RW, K: GND VDD, A (220 Ω): +5 V V0: 10 kΩ pot wiper (contrast) RS: PA0 (pin 40) EN: PA1 (pin 39) D4: PA4 (pin 36) D5: PA5 (pin 35) D6: PA6 (pin 34) D7: PA7 (pin 33) 4×4 Keypad R1-R4: PC0-PC3 (pins 22-25) C1-C4: PC4-PC7 (pins 26-29) Internal pull-ups on columns SG90 Servo Orange (signal): PD5 / OC1A (pin 19) Red: +5 V (separate 5 V 1 A supply) Brown: GND (common with ATmega16) Buzzer and LEDs Active buzzer +: PD6 (pin 20), −: GND Green LED: 220 Ω to PD2 (pin 16) Red LED: 220 Ω to PD3 (pin 17)
Pin-accurate connection diagram for the ATmega16 keypad password door lock.

AVR C Code

The program is plain AVR C and needs only avr-libc, so it builds in Microchip Studio, or with avr-gcc on the command line. It compiles to about 2 KB of flash. Build and flash it with a USBasp like this:

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

The fuse values select the external 16 MHz crystal (low fuse 0xFF) and turn JTAG off (high fuse 0xD9). Set the fuses once before you flash the program, and double-check them, because a wrong clock fuse makes the chip stop responding until an external clock is supplied.

/*
 * ATmega16 Keypad Password Door Lock with 16x2 LCD & Servo
 * ardiunoprojecthub.online
 *
 * MCU   : ATmega16 @ 16 MHz external crystal
 * Fuses : lfuse=0xFF (ext. crystal), hfuse=0xD9 (JTAG off, SPI on)
 *         (JTAG is also switched off in code, so PORTC works either way)
 *
 * LCD 16x2 (4-bit): RS=PA0, EN=PA1, D4=PA4, D5=PA5, D6=PA6, D7=PA7, RW=GND
 * 4x4 keypad      : rows R1..R4 = PC0..PC3, columns C1..C4 = PC4..PC7
 * Servo SG90      : signal = PD5 (OC1A, hardware 50 Hz PWM)
 * Green LED       : PD2 (unlocked)   Red LED: PD3 (locked)
 * Buzzer (active) : PD6
 *
 * Keys: 0-9 = digits, '#' = enter, '*' = clear,
 *       'A' = change password (enter old one first), 'D' = lock now
 * Default password: 1234 (stored in EEPROM, 4 to 8 digits)
 */
#define F_CPU 16000000UL
#include <avr/io.h>
#include <avr/eeprom.h>
#include <util/delay.h>
#include <string.h>

#define MAX_LEN      8
#define MIN_LEN      4
#define MAX_TRIES    3
#define LOCKOUT_SEC  30
#define UNLOCK_SEC   5

#define SERVO_LOCKED   2000   /* 1.0 ms pulse (0.5 us per tick) */
#define SERVO_UNLOCKED 4000   /* 2.0 ms pulse */

/* EEPROM layout: byte 0 = magic, byte 1 = length, bytes 2.. = digits */
#define EE_MAGIC 0xA5
uint8_t EEMEM ee_magic;
uint8_t EEMEM ee_len;
char    EEMEM ee_pass[MAX_LEN];

static char password[MAX_LEN + 1];

/* ---------------- LCD (HD44780, 4-bit mode on PORTA) ---------------- */
#define LCD_RS PA0
#define LCD_EN PA1

static void lcd_pulse(void) {
    PORTA |= (1 << LCD_EN); _delay_us(1);
    PORTA &= ~(1 << LCD_EN); _delay_us(50);
}
static void lcd_nibble(uint8_t n) {           /* n = high nibble already in bits 7..4 */
    PORTA = (PORTA & 0x0F) | (n & 0xF0);
    lcd_pulse();
}
static void lcd_send(uint8_t v, uint8_t rs) {
    if (rs) PORTA |= (1 << LCD_RS); else PORTA &= ~(1 << LCD_RS);
    lcd_nibble(v);
    lcd_nibble(v << 4);
}
static void lcd_cmd(uint8_t c)  { lcd_send(c, 0); if (c < 4) _delay_ms(2); }
static void lcd_char(char c)    { lcd_send(c, 1); }
static void lcd_print(const char *s) { while (*s) lcd_char(*s++); }
static void lcd_goto(uint8_t col, uint8_t row) { lcd_cmd(0x80 | (row ? 0x40 : 0x00) | col); }
static void lcd_clear(void)     { lcd_cmd(0x01); }

static void lcd_init(void) {
    DDRA |= 0xF3;                       /* PA0, PA1, PA4..PA7 as outputs */
    _delay_ms(50);
    PORTA &= ~(1 << LCD_RS);
    lcd_nibble(0x30); _delay_ms(5);     /* wake-up sequence */
    lcd_nibble(0x30); _delay_us(150);
    lcd_nibble(0x30);
    lcd_nibble(0x20);                   /* switch to 4-bit */
    lcd_cmd(0x28);                      /* 2 lines, 5x8 font */
    lcd_cmd(0x0C);                      /* display on, cursor off */
    lcd_cmd(0x06);                      /* auto-increment */
    lcd_clear();
}
static void lcd_two(const char *l1, const char *l2) {
    lcd_clear();
    lcd_goto(0, 0); lcd_print(l1);
    lcd_goto(0, 1); lcd_print(l2);
}

/* ---------------- 4x4 keypad on PORTC ---------------- */
static const char keymap[4][4] = {
    {'1', '2', '3', 'A'},
    {'4', '5', '6', 'B'},
    {'7', '8', '9', 'C'},
    {'*', '0', '#', 'D'}
};

static void keypad_init(void) {
    DDRC  = 0x0F;     /* rows PC0..PC3 outputs, columns PC4..PC7 inputs */
    PORTC = 0xFF;     /* rows high, pull-ups on columns */
}

/* Returns a key or 0 if nothing is pressed (with debounce + wait for release) */
static char keypad_get(void) {
    for (uint8_t r = 0; r < 4; r++) {
        PORTC = (PORTC | 0x0F) & ~(1 << r);   /* pull one row low */
        _delay_us(5);
        uint8_t cols = PINC >> 4;
        for (uint8_t c = 0; c < 4; c++) {
            if (!(cols & (1 << c))) {
                _delay_ms(20);                 /* debounce */
                if (!((PINC >> 4) & (1 << c))) {
                    while (!((PINC >> 4) & (1 << c)));  /* wait for release */
                    _delay_ms(20);
                    PORTC |= 0x0F;
                    return keymap[r][c];
                }
            }
        }
    }
    PORTC |= 0x0F;
    return 0;
}

/* ---------------- Servo, LEDs, buzzer ---------------- */
static void servo_init(void) {
    DDRD |= (1 << PD5);
    /* Timer1 fast PWM mode 14 (TOP = ICR1), non-inverting on OC1A, prescaler 8 */
    TCCR1A = (1 << COM1A1) | (1 << WGM11);
    TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS11);
    ICR1   = 39999;                     /* 16 MHz / 8 / 40000 = 50 Hz */
    OCR1A  = SERVO_LOCKED;
}

static void beep(uint16_t ms) {
    PORTD |= (1 << PD6);
    while (ms--) _delay_ms(1);
    PORTD &= ~(1 << PD6);
}

static void set_locked(uint8_t locked) {
    OCR1A = locked ? SERVO_LOCKED : SERVO_UNLOCKED;
    if (locked) { PORTD |= (1 << PD3); PORTD &= ~(1 << PD2); }
    else        { PORTD |= (1 << PD2); PORTD &= ~(1 << PD3); }
}

/* ---------------- Password storage ---------------- */
static void load_password(void) {
    uint8_t len = eeprom_read_byte(&ee_len);
    if (eeprom_read_byte(&ee_magic) != EE_MAGIC || len < MIN_LEN || len > MAX_LEN) {
        strcpy(password, "1234");                    /* first boot: default */
        eeprom_update_byte(&ee_len, 4);
        eeprom_update_block(password, ee_pass, 4);
        eeprom_update_byte(&ee_magic, EE_MAGIC);
        return;
    }
    eeprom_read_block(password, ee_pass, len);
    password[len] = '\0';
}

static void save_password(const char *p) {
    uint8_t len = strlen(p);
    eeprom_update_block(p, ee_pass, len);
    eeprom_update_byte(&ee_len, len);
    strcpy(password, p);
}

/* Read digits until '#'. Shows '*' for each digit. Returns length, or -1 on 'D'. */
static int8_t read_code(const char *prompt, char *buf) {
    uint8_t n = 0;
    lcd_two(prompt, "");
    lcd_goto(0, 1);
    for (;;) {
        char k = keypad_get();
        if (!k) continue;
        beep(30);
        if (k >= '0' && k <= '9') {
            if (n < MAX_LEN) { buf[n++] = k; lcd_char('*'); }
        } else if (k == '*') {                 /* clear entry */
            n = 0;
            lcd_two(prompt, "");
            lcd_goto(0, 1);
        } else if (k == '#') {                 /* enter */
            buf[n] = '\0';
            return n;
        } else if (k == 'A') {                 /* change password request */
            buf[0] = 'A'; buf[1] = '\0';
            return 1;
        } else if (k == 'D') {
            return -1;
        }
    }
}

static void change_password(void) {
    char buf[MAX_LEN + 1], again[MAX_LEN + 1];
    if (read_code("Old password:", buf) < 0 || strcmp(buf, password) != 0) {
        lcd_two("Wrong password", "Not changed"); beep(400); _delay_ms(1500);
        return;
    }
    int8_t n = read_code("New (4-8 digit):", buf);
    if (n < MIN_LEN || buf[0] == 'A') {
        lcd_two("Too short", "Not changed"); beep(400); _delay_ms(1500);
        return;
    }
    read_code("Repeat new:", again);
    if (strcmp(buf, again) != 0) {
        lcd_two("No match", "Not changed"); beep(400); _delay_ms(1500);
        return;
    }
    save_password(buf);
    lcd_two("Password saved", ""); beep(100); _delay_ms(100); beep(100);
    _delay_ms(1500);
}

int main(void) {
    /* Disable JTAG at run time (write JTD twice within 4 cycles) so PORTC is free */
    MCUCSR |= (1 << JTD);
    MCUCSR |= (1 << JTD);

    DDRD |= (1 << PD2) | (1 << PD3) | (1 << PD6);
    lcd_init();
    keypad_init();
    servo_init();
    set_locked(1);
    load_password();

    lcd_two(" Keypad  Lock", " ATmega16 Ready");
    beep(100);
    _delay_ms(1500);

    uint8_t wrong = 0;
    char entry[MAX_LEN + 1];

    for (;;) {
        int8_t n = read_code("Enter password:", entry);
        if (n < 0) continue;                       /* 'D' while locked: nothing to do */
        if (entry[0] == 'A') { change_password(); continue; }

        if (strcmp(entry, password) == 0) {
            wrong = 0;
            set_locked(0);
            lcd_two("Access granted", "Door unlocked");
            beep(80); _delay_ms(80); beep(80);
            /* stay open for UNLOCK_SEC or until 'D' is pressed */
            for (uint16_t t = 0; t < UNLOCK_SEC * 100; t++) {
                if (keypad_get() == 'D') break;
                _delay_ms(10);
            }
            set_locked(1);
            lcd_two("Door locked", "");
            _delay_ms(1000);
        } else {
            wrong++;
            lcd_two("Wrong password", "");
            lcd_goto(0, 1);
            lcd_print("Tries left: ");
            lcd_char('0' + (MAX_TRIES - wrong));
            beep(500);
            _delay_ms(1500);
            if (wrong >= MAX_TRIES) {
                /* lockout with countdown and alarm beeps */
                for (int8_t s = LOCKOUT_SEC; s > 0; s--) {
                    lcd_two("LOCKED OUT!", "Wait ");
                    lcd_char('0' + s / 10); lcd_char('0' + s % 10);
                    lcd_print(" sec");
                    PORTD ^= (1 << PD3);
                    beep(200);
                    _delay_ms(800);
                }
                set_locked(1);
                wrong = 0;
            }
        }
    }
}

Testing

  • Power up: the LCD shows “Keypad Lock / ATmega16 Ready”, the red LED is on and the servo moves to the locked position.
  • Type 1234 and press #. The green LED turns on, the servo opens and after 5 seconds it locks again.
  • Enter a wrong code three times to see the 30 second lockout countdown.
  • Press A, enter 1234, then a new password twice. Switch off and on again to confirm it was saved.

Troubleshooting

ProblemFix
LCD shows only black boxesTurn the contrast pot slowly. If it still shows boxes, check RS, EN and D4 to D7 and that RW is tied to GND.
Some keypad columns do not workPC2 to PC5 are JTAG pins. Make sure the high fuse is 0xD9 (JTAG off); the code also disables JTAG at start-up.
Wrong keys are detectedYour keypad’s pin order may differ. Swap rows and columns in the table until each key shows the right digit, or edit keymap.
Servo jitters or the chip resets when it movesPower the servo from a separate 5 V supply and connect the grounds together. Add a 470 µF capacitor across the servo supply.
Timing is very slowThe chip is still on its internal 1 MHz clock. Program the low fuse to 0xFF for the external 16 MHz crystal.

Ideas to Extend

  • Drive a 12 V solenoid door lock through a relay module or logic-level MOSFET instead of the servo.
  • Add an RC522 RFID reader so either a card or the password opens the door.
  • Add an HC-05 Bluetooth module to unlock from a phone, or a door reed switch to re-lock only after the door closes.

ATmega16 Ultrasonic Parking Sensor with LED Bar & Buzzer

ATmega16 ultrasonic parking sensor wiring with HC-SR04, LED bar graph and buzzer

Build an ATmega16 ultrasonic parking sensor with HC-SR04, an 8-LED bar graph and a buzzer that beeps faster as you get closer. Wiring table, diagram and full AVR C code.

  • DifficultyEasy
  • Build time1–2 hours
  • Board / MCUATmega16
  • Parts11 items
  • CodeAVR C

Need it ready-made? Buy Ready Project

This ATmega16 ultrasonic parking sensor helps you park a car, scooter or garage cart without bumping into the wall. An HC-SR04 ultrasonic sensor measures the distance, an 8-LED bar graph (green, yellow, red) lights up more as you get closer, and a buzzer beeps faster and faster until it gives a continuous tone at the stop point.

It is a small, beginner-friendly AVR project written in plain AVR C. You will learn how to make a trigger pulse, time an echo with Timer1, filter noisy readings and drive an LED bar graph from one port.

ATmega16 ultrasonic parking sensor wiring with HC-SR04, LED bar graph and buzzer

How It Works

  • Measuring distance: the ATmega16 sends a 10 µs pulse on TRIG. The HC-SR04 fires a 40 kHz burst and holds ECHO high for as long as the sound takes to come back. Timer1 runs at 2 MHz (16 MHz ÷ 8), so each tick is 0.5 µs, and distance in cm = ticks ÷ 116.
  • Filtering: three readings are taken 30 ms apart and the middle (median) value is used, so a single wrong echo does not make the LEDs jump.
  • LED bar graph: from 150 cm down to 10 cm the distance is mapped to 1 to 8 LEDs on PORTA. Green means plenty of room, yellow means slow down, red means almost there.
  • Buzzer: the gap between beeps shrinks from about 800 ms far away to about 60 ms near the stop point. Below 10 cm all LEDs light and the buzzer stays on continuously.
  • Out of range: beyond 150 cm, or when no echo arrives, everything stays off and silent so it does not disturb you.

Components Required

  • ATmega16 (or ATmega16A) microcontroller, DIP-40 – 1
  • 16 MHz crystal with two 22 pF capacitors – 1 set
  • HC-SR04 ultrasonic sensor – 1
  • 5 mm LEDs: 3 green, 3 yellow, 2 red – 8
  • 330 Ω resistors – 8
  • 10 kΩ resistor (reset pull-up) – 1
  • 5 V active buzzer – 1
  • 7805 voltage regulator with 0.33 µF and 0.1 µF capacitors – 1
  • 0.1 µF decoupling capacitors – 2
  • 9–12 V DC adapter, breadboard or perfboard, jumper wires
  • USBasp programmer (to flash the chip)

Wiring Table

Component pinATmega16 pinNotes
HC-SR04 VCC+5 VFrom the 7805 output
HC-SR04 TRIGPD5 (pin 19)Output
HC-SR04 ECHOPD6 (pin 20)Input, 5 V logic is fine
HC-SR04 GNDGND
LED1–LED3 (green)PA0–PA2 (pins 40–38)Each through 330 Ω, cathode to GND
LED4–LED6 (yellow)PA3–PA5 (pins 37–35)Each through 330 Ω, cathode to GND
LED7–LED8 (red)PA6–PA7 (pins 34–33)Each through 330 Ω, cathode to GND
Buzzer +PD7 (pin 21)Buzzer – to GND
16 MHz crystalXTAL1 (13), XTAL2 (12)22 pF from each pin to GND
ResetRESET (pin 9)10 kΩ to +5 V
PowerVCC (10), AVCC (30)+5 V, 0.1 µF to GND at each
GroundGND (11, 31)Common ground for everything

Connection Diagram

The illustration above shows the general layout. The pin-accurate drawing below matches the wiring table exactly, so follow it when you wire the circuit.

ATmega16 Ultrasonic Parking Sensor – Pin-Accurate Wiring PA0 (pin 40) LED1 green + 330 ohm to GND (far) PA1 (pin 39) LED2 green + 330 ohm to GND PA2 (pin 38) LED3 green + 330 ohm to GND PA3 (pin 37) LED4 yellow + 330 ohm to GND PA4 (pin 36) LED5 yellow + 330 ohm to GND PA5 (pin 35) LED6 yellow + 330 ohm to GND PA6 (pin 34) LED7 red + 330 ohm to GND PA7 (pin 33) LED8 red + 330 ohm to GND (STOP) PD5 (pin 19) HC-SR04 TRIG PD6 (pin 20) HC-SR04 ECHO PD7 (pin 21) Active buzzer + (buzzer – to GND) XTAL1/XTAL2 (13/12) 16 MHz crystal, 22 pF from each pin to GND RESET (pin 9) 10k to +5 V VCC 10, AVCC 30 +5 V from 7805 (0.1 uF at each pin) GND 11, GND 31 GND (HC-SR04 GND, buzzer -, LED cathodes) HC-SR04 VCC to +5 V. 7805 input: 9-12 V adapter, 0.33 uF in and 0.1 uF out.
Pin-accurate connection diagram for the ATmega16 ultrasonic parking sensor.

AVR C Code

Compile with Microchip Studio or avr-gcc for the atmega16 at 16 MHz. No external libraries are needed and the program is only about 720 bytes.

/*
  ATmega16 Ultrasonic Car Parking Sensor
  HC-SR04 ultrasonic sensor + 8-LED bar graph + active buzzer
  Compiler : AVR-GCC (Microchip Studio, or avr-gcc + avrdude)
  Clock    : 16 MHz external crystal (fuses: lfuse 0xFF, hfuse 0xD9 - JTAG disabled)

  Wiring
    HC-SR04 TRIG -> PD5        HC-SR04 ECHO -> PD6
    LED1..LED8 (green, green, green, yellow, yellow, yellow, red, red)
               -> PA0..PA7, each through a 330 ohm resistor to GND
    Active buzzer + -> PD7 (buzzer - to GND)
    All modules run from the same regulated +5 V and share GND.

  Behaviour
    > 150 cm      : all LEDs off, buzzer silent
    150 .. 10 cm  : more LEDs light as the car gets closer,
                    buzzer beeps faster and faster
    < 10 cm       : all 8 LEDs on and a continuous tone = STOP
*/

#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <stdint.h>

#define TRIG_PIN   PD5
#define ECHO_PIN   PD6
#define BUZZER_PIN PD7

#define MAX_CM   150   // beyond this distance the sensor stays quiet
#define STOP_CM   10   // closer than this = continuous tone

/* Send a 10 us trigger pulse and time the echo with Timer1.
   Timer1 runs at 16 MHz / 8 = 2 MHz, so 1 tick = 0.5 us.
   Returns the distance in cm, or 0xFFFF if there was no echo. */
static uint16_t read_distance_cm(void)
{
    uint16_t ticks;

    PORTD &= ~(1 << TRIG_PIN);
    _delay_us(4);
    PORTD |= (1 << TRIG_PIN);
    _delay_us(10);
    PORTD &= ~(1 << TRIG_PIN);

    /* wait for the echo line to go HIGH (max ~30 ms) */
    TCNT1 = 0;
    TCCR1B = (1 << CS11);                 // start Timer1, prescaler 8
    while (!(PIND & (1 << ECHO_PIN))) {
        if (TCNT1 > 60000) { TCCR1B = 0; return 0xFFFF; }
    }

    /* measure how long ECHO stays HIGH */
    TCNT1 = 0;
    while (PIND & (1 << ECHO_PIN)) {
        if (TCNT1 > 60000) { TCCR1B = 0; return 0xFFFF; }   // > 5 m, out of range
    }
    ticks = TCNT1;
    TCCR1B = 0;                           // stop Timer1

    /* echo time in us = ticks / 2 ; distance cm = us / 58  ->  ticks / 116 */
    return ticks / 116;
}

/* Median of three readings removes odd spikes from the sensor. */
static uint16_t read_filtered_cm(void)
{
    uint16_t a, b, c, t;
    a = read_distance_cm(); _delay_ms(30);
    b = read_distance_cm(); _delay_ms(30);
    c = read_distance_cm();
    if (a > b) { t = a; a = b; b = t; }
    if (b > c) { t = b; b = c; c = t; }
    if (a > b) { t = a; a = b; b = t; }
    return b;
}

/* Show 0..8 LEDs on PORTA as a bar graph. */
static void show_bar(uint8_t leds)
{
    PORTA = (leds >= 8) ? 0xFF : (uint8_t)((1 << leds) - 1);
}

/* Variable delay in 10 ms steps (_delay_ms needs a constant). */
static void wait_10ms(uint8_t n)
{
    while (n--) _delay_ms(10);
}

int main(void)
{
    DDRA = 0xFF;                                   // LEDs as outputs
    PORTA = 0x00;
    DDRD |= (1 << TRIG_PIN) | (1 << BUZZER_PIN);   // trigger + buzzer outputs
    DDRD &= ~(1 << ECHO_PIN);                      // echo input
    PORTD &= ~((1 << TRIG_PIN) | (1 << BUZZER_PIN));

    /* power-on self test: sweep the LED bar and give one short beep */
    for (uint8_t i = 0; i <= 8; i++) { show_bar(i); _delay_ms(60); }
    PORTD |= (1 << BUZZER_PIN); _delay_ms(100); PORTD &= ~(1 << BUZZER_PIN);
    show_bar(0);

    while (1) {
        uint16_t cm = read_filtered_cm();

        if (cm >= MAX_CM) {                        // nothing near (or no echo)
            show_bar(0);
            PORTD &= ~(1 << BUZZER_PIN);
            _delay_ms(100);
        }
        else if (cm < STOP_CM) {                   // too close: STOP
            show_bar(8);
            PORTD |= (1 << BUZZER_PIN);            // continuous tone
            _delay_ms(100);
        }
        else {
            /* map 150..10 cm to 1..8 LEDs */
            uint8_t leds = 1 + (uint8_t)(((MAX_CM - cm) * 7UL) / (MAX_CM - STOP_CM));
            show_bar(leds);

            /* beep gap: about 800 ms far away, about 60 ms when very close */
            uint8_t gap10 = 6 + (uint8_t)(((cm - STOP_CM) * 74UL) / (MAX_CM - STOP_CM));
            PORTD |= (1 << BUZZER_PIN);
            _delay_ms(50);
            PORTD &= ~(1 << BUZZER_PIN);
            wait_10ms(gap10);
        }
    }
}

Compiling and Flashing

With avr-gcc and avrdude and a USBasp programmer, run these commands:

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

The fuse values select the external 16 MHz crystal and disable JTAG. Write the fuses only once and double-check them before you do.

Mounting and Testing

  • Power it up. All 8 LEDs should sweep on and the buzzer should beep once.
  • Move your hand slowly towards the sensor from about 1.5 m away. LEDs should light one by one and the beeps should speed up.
  • Below 10 cm all LEDs should be on with a continuous tone.
  • Mount the sensor on the garage wall at bumper height, facing straight out. Put the LED bar where the driver can see it.
  • Change MAX_CM and STOP_CM in the code to suit your parking space.

Troubleshooting

ProblemFix
Nothing happens at allCheck the crystal and fuses. If the fuses are still factory default (1 MHz internal), delays will be 16 times slower.
LEDs always offCheck TRIG/ECHO are not swapped and the sensor has 5 V.
Readings jump aroundKeep the sensor away from soft surfaces and add a 100 µF capacitor across the sensor supply.
PORTA pins do not respondPORTA is also the ADC port; make sure AVCC (pin 30) is connected to +5 V.

Ideas to Extend

  • Add a 16×2 LCD to show the exact distance in cm.
  • Add a second sensor for the rear corner of the car.
  • Use an ULN2003 to drive a bright LED strip as a big red STOP light.

ATmega16 Bluetooth Home Automation with HC-05, 4 Relays & LCD

ATmega16 Bluetooth home automation connection diagram with HC-05, 16x2 LCD, 4-channel relay module, buttons and 7805 regulator

Build an ATmega16 Bluetooth home automation system with HC-05, a 4-channel relay module, 16×2 LCD and manual buttons. Wiring table, diagram and full AVR C code.

  • DifficultyAdvanced
  • Build time5–8 hours
  • Board / MCUATmega16
  • Parts12 items
  • CodeAVR C

Need it ready-made? Buy Ready Project

This ATmega16 Bluetooth home automation project lets you switch four home appliances ON and OFF from your Android phone using an HC-05 Bluetooth module, a 4-channel relay module and a 16×2 LCD that shows the live status of every relay. Four push buttons on the board also work as manual switches, so the lights still work even when the phone is not connected.

It is a big combination project: it uses the ATmega16 hardware UART with an interrupt, a 4-bit LCD driver written from scratch, debounced buttons and relay control, all in plain AVR C with no Arduino libraries. It is a great step up for students who already know basic AVR programming.

How the Bluetooth Home Automation Works

  • Phone to HC-05: a free Bluetooth terminal app on the phone sends single characters. The HC-05 receives them over Bluetooth and passes them to the ATmega16 over serial at 9600 baud.
  • UART interrupt: every received byte triggers the USART_RXC interrupt, which stores it. The main loop reads it and decides what to do.
  • Commands: 1–4 turn relay 1–4 ON, a–d turn them OFF, A turns all ON, Z turns all OFF and S sends the status back to the phone.
  • Manual buttons: SW1–SW4 on PA0–PA3 toggle the matching relay. The code uses internal pull-ups and a 30 ms software debounce.
  • LCD feedback: the 16×2 LCD shows R1 to R4 on the first line and ON or OFF under each one. Every change is also sent back to the phone.
  • Relay driver: the relay module has its own transistor and opto-coupler, so the ATmega16 pins drive the IN pins directly. Most modules are active LOW, which is set with RELAY_ACTIVE_LOW.

Components Required

  • ATmega16 / ATmega16A microcontroller (DIP-40) – 1
  • HC-05 Bluetooth module – 1
  • 4-channel 5 V relay module (opto-isolated) – 1
  • 16×2 character LCD (HD44780) – 1
  • 10 kΩ potentiometer (LCD contrast) – 1
  • 16 MHz crystal and 2 × 22 pF capacitors
  • Tactile push buttons – 4
  • Resistors: 1 kΩ, 2 kΩ (HC-05 RX divider), 10 kΩ (reset pull-up), 330 Ω (LED)
  • Status LED – 1
  • 7805 voltage regulator with 10 µF and 100 µF capacitors, plus 100 nF decoupling capacitors
  • 12 V DC adapter (1 A) and DC jack
  • USBasp programmer, breadboard or perfboard, jumper wires

Wiring Table (Pin-to-Pin)

Part / PinATmega16 pinNotes
HC-05 TXDPD0 / RXD (pin 14)Data from phone to MCU
HC-05 RXDPD1 / TXD (pin 15)Through 1 kΩ, with 2 kΩ from HC-05 RXD to GND (5 V to 3.3 V divider)
HC-05 VCC / GND+5 V / GNDThe HC-05 board has its own 3.3 V regulator
LCD RSPC0 (pin 22)Register select
LCD EPC1 (pin 23)Enable
LCD D4, D5, D6, D7PC2, PC3, PC4, PC5 (pins 24–27)4-bit data bus
LCD RWGNDWrite only
LCD V010 kΩ pot wiperPot ends to +5 V and GND
LCD VSS / VDD / A / KGND / +5 V / +5 V (via 220 Ω) / GNDPower and backlight
Relay IN1, IN2, IN3, IN4PB0, PB1, PB2, PB3 (pins 1–4)Relay VCC to +5 V, GND to GND
SW1, SW2, SW3, SW4PA0, PA1, PA2, PA3 (pins 40, 39, 38, 37)Other leg of each button to GND
Status LEDPD7 (pin 21)Through 330 Ω to GND
16 MHz crystalXTAL1 (12) and XTAL2 (13)22 pF from each pin to GND
VCC, AVCCPins 10 and 30+5 V from 7805, 100 nF to GND near each pin
GNDPins 11 and 31Common ground for all modules
RESETPin 910 kΩ pull-up to +5 V

Connection Diagram

The picture below gives an overview of the whole build. The pin-accurate drawing after it matches the wiring table and the code exactly, so follow the table and that drawing when you wire the board.

ATmega16 Bluetooth home automation connection diagram with HC-05, 16x2 LCD, 4-channel relay module, buttons and 7805 regulator
ATmega16 Bluetooth Home Automation – Pin-Accurate Wiring ATmega16 (DIP-40) PD0 (RXD, pin 14) HC-05 TXD PD1 (TXD, pin 15) 1 kΩ → HC-05 RXD (2 kΩ from RXD to GND) PC0 / PC1 (pins 22, 23) LCD RS / E PC2–PC5 (pins 24–27) LCD D4–D7 (RW → GND, 10 kΩ pot → V0) PB0–PB3 (pins 1–4) Relay module IN1–IN4 PA0–PA3 (pins 40–37) Buttons SW1–SW4 → GND (internal pull-ups) PD7 (pin 21) 330 Ω → status LED → GND XTAL1 / XTAL2 (12, 13) 16 MHz crystal + 22 pF to GND on each pin VCC, AVCC (10, 30) +5 V from 7805 (100 nF to GND) GND (11, 31) Common GND: HC-05, LCD, relays, 7805 RESET (pin 9) 10 kΩ to +5 V Relay module VCC: +5 V (7805 rated 1 A, add a heatsink). Mains wiring only by a qualified person.
Pin-accurate connection diagram for the ATmega16 Bluetooth home automation.

ATmega16 Code (AVR C)

Create a new GCC C project for the ATmega16 in Microchip Studio (or use avr-gcc), paste the code and build it. Flash the HEX with a USBasp and set the fuses to lfuse 0xFF and hfuse 0xD9 for the 16 MHz external crystal with JTAG disabled. The code is fully commented and compiles without errors for the ATmega16 (about 1 KB of flash).

/*
  ATmega16 Bluetooth Home Automation
  HC-05 Bluetooth + 4-channel relay module + 16x2 LCD (4-bit) + 4 manual buttons
  Compiler : AVR-GCC (Microchip Studio, or avr-gcc + avrdude)
  Clock    : 16 MHz external crystal  (fuses: lfuse 0xFF, hfuse 0xD9 - JTAG disabled)

  Wiring
    HC-05 TXD -> PD0 (RXD)      HC-05 RXD <- PD1 (TXD) through 1k/2k divider
    LCD RS -> PC0   E -> PC1   D4..D7 -> PC2..PC5   RW -> GND
    Relay IN1..IN4 -> PB0..PB3
    Buttons SW1..SW4 -> PA0..PA3 to GND (internal pull-ups)
    Status LED -> PD7 (330 ohm)

  Bluetooth commands (send from any "Bluetooth Terminal" phone app, 9600 baud)
    '1'..'4'  turn relay 1..4 ON
    'a'..'d'  turn relay 1..4 OFF
    'A'       all ON        'Z'  all OFF
    'S'       send status back to the phone
*/

#define F_CPU 16000000UL
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <stdint.h>

#define BAUD 9600
#define UBRR_VALUE ((F_CPU / 16UL / BAUD) - 1)

#define RELAY_ACTIVE_LOW 1      // most blue relay modules switch ON when IN is LOW

#define LCD_RS PC0
#define LCD_E  PC1
#define LED_PIN PD7

static volatile uint8_t rx_char = 0;    // last character received (0 = none)
static uint8_t relay_state = 0;         // bit0..bit3 = relay 1..4 (1 = ON)

/* ---------------- LCD (4-bit, PORTC) ---------------- */
static void lcd_nibble(uint8_t n) {
  PORTC = (PORTC & 0xC3) | ((n & 0x0F) << 2);   // D4..D7 on PC2..PC5
  PORTC |= (1 << LCD_E);
  _delay_us(1);
  PORTC &= ~(1 << LCD_E);
  _delay_us(50);
}

static void lcd_send(uint8_t value, uint8_t is_data) {
  if (is_data) PORTC |= (1 << LCD_RS); else PORTC &= ~(1 << LCD_RS);
  lcd_nibble(value >> 4);
  lcd_nibble(value);
  if (!is_data && value < 4) _delay_ms(2);        // clear and home need more time
}

static void lcd_cmd(uint8_t c)  { lcd_send(c, 0); }
static void lcd_char(char c)    { lcd_send((uint8_t)c, 1); }
static void lcd_print(const char *s) { while (*s) lcd_char(*s++); }
static void lcd_goto(uint8_t row, uint8_t col) { lcd_cmd(0x80 | (row ? 0x40 : 0x00) | col); }

static void lcd_init(void) {
  DDRC |= 0x3F;                  // PC0..PC5 outputs
  _delay_ms(50);                 // LCD power-up time
  PORTC &= ~(1 << LCD_RS);
  lcd_nibble(0x03); _delay_ms(5);
  lcd_nibble(0x03); _delay_ms(1);
  lcd_nibble(0x03);
  lcd_nibble(0x02);              // 4-bit mode
  lcd_cmd(0x28);                 // 2 lines, 5x8 font
  lcd_cmd(0x0C);                 // display on, cursor off
  lcd_cmd(0x06);                 // auto-increment
  lcd_cmd(0x01);                 // clear
}

/* ---------------- UART (HC-05) ---------------- */
static void uart_init(void) {
  UBRRH = (uint8_t)(UBRR_VALUE >> 8);
  UBRRL = (uint8_t)UBRR_VALUE;
  UCSRB = (1 << RXEN) | (1 << TXEN) | (1 << RXCIE);       // RX, TX, RX interrupt
  UCSRC = (1 << URSEL) | (1 << UCSZ1) | (1 << UCSZ0);     // 8 data bits, 1 stop, no parity
}

static void uart_putc(char c) {
  while (!(UCSRA & (1 << UDRE)));  // wait until the transmit buffer is empty
  UDR = c;
}

static void uart_print(const char *s) { while (*s) uart_putc(*s++); }

ISR(USART_RXC_vect) {
  rx_char = UDR;                   // store the byte; main loop handles it
}

/* ---------------- Relays ---------------- */
static void relays_apply(void) {
  uint8_t out = relay_state & 0x0F;
  if (RELAY_ACTIVE_LOW) out = (~out) & 0x0F;
  PORTB = (PORTB & 0xF0) | out;    // PB0..PB3
}

static void show_status(void) {
  // Line 1: "R1 R2 R3 R4", line 2: "ON OF ON OF"
  lcd_goto(0, 0);
  lcd_print("R1  R2  R3  R4  ");
  lcd_goto(1, 0);
  for (uint8_t i = 0; i < 4; i++) {
    lcd_print((relay_state & (1 << i)) ? "ON  " : "OFF ");
  }
}

static void send_status(void) {
  uart_print("Status: ");
  for (uint8_t i = 0; i < 4; i++) {
    uart_putc('R'); uart_putc('1' + i); uart_putc('=');
    uart_print((relay_state & (1 << i)) ? "ON " : "OFF ");
  }
  uart_print("\r\n");
}

static void handle_command(char c) {
  if (c >= '1' && c <= '4')      relay_state |=  (1 << (c - '1'));
  else if (c >= 'a' && c <= 'd') relay_state &= ~(1 << (c - 'a'));
  else if (c == 'A')             relay_state = 0x0F;
  else if (c == 'Z')             relay_state = 0x00;
  else if (c == 'S')           { send_status(); return; }
  else return;                    // ignore newline and unknown characters
  relays_apply();
  show_status();
  send_status();
  PORTD ^= (1 << LED_PIN);        // blink LED on every valid command
}

/* ---------------- Buttons (PA0..PA3, active LOW) ---------------- */
static void check_buttons(void) {
  static uint8_t last = 0x0F;     // all released (pull-ups)
  uint8_t now = PINA & 0x0F;
  uint8_t pressed = last & ~now;  // bits that went from 1 to 0
  if (pressed) {
    _delay_ms(30);                // debounce
    now = PINA & 0x0F;
    pressed &= ~now;              // still pressed after debounce
    if (pressed) {
      relay_state ^= pressed;     // toggle the matching relay(s)
      relays_apply();
      show_status();
      send_status();
    }
  }
  last = now;
}

int main(void) {
  DDRB |= 0x0F;                   // relay outputs
  relays_apply();                 // start with all relays OFF
  DDRA &= ~0x0F;                  // buttons as inputs
  PORTA |= 0x0F;                  // enable pull-ups
  DDRD |= (1 << LED_PIN);

  lcd_init();
  lcd_goto(0, 0); lcd_print("BT Home Control");
  lcd_goto(1, 0); lcd_print("ATmega16 Ready ");
  _delay_ms(1500);

  uart_init();
  sei();                          // enable global interrupts
  uart_print("ATmega16 Home Automation ready\r\n");
  show_status();

  while (1) {
    if (rx_char) {
      char c;
      cli(); c = rx_char; rx_char = 0; sei();
      handle_command(c);
    }
    check_buttons();
    _delay_ms(5);
  }
}

Example command line build and flash:

avr-gcc -mmcu=atmega16 -Os -o bt.elf atmega16_bt_home_automation.c
avr-objcopy -O ihex bt.elf bt.hex
avrdude -c usbasp -p m16 -U flash:w:bt.hex -U lfuse:w:0xFF:m -U hfuse:w:0xD9:m

How to Use It From Your Phone

  • Power the board and pair your phone with the HC-05 (default PIN is 1234 or 0000).
  • Open any free Bluetooth serial terminal app and connect to the HC-05.
  • Send 1 to switch on relay 1, a to switch it off, A for all on, Z for all off and S to get the status.
  • Many apps let you make buttons that send these characters, which gives you a simple remote control screen.

Troubleshooting

ProblemFix
LCD shows black boxes onlyAdjust the 10 kΩ contrast pot and check the RS, E and D4–D7 wires.
Phone sends commands but nothing happensCheck that HC-05 TXD goes to PD0 and that the baud rate is 9600. Make sure the fuses select the 16 MHz crystal, or the baud rate will be wrong.
Relays work the opposite waySet RELAY_ACTIVE_LOW to 0 for an active-HIGH relay module.
Board resets when a relay clicksUse a 1 A adapter, add a 470 µF capacitor on the 5 V rail and power the relay coils from a separate JD-VCC supply.
PORTC pins do not workJTAG is enabled. Program hfuse 0xD9 to disable JTAG so PC2–PC5 work as normal I/O.

Safety and Ideas to Extend

  • Switching 230 V AC is dangerous. Test with low-voltage lamps first, keep the mains side in a closed box and let a qualified person do the mains wiring.
  • Use relays rated for your load and add a fuse on the mains side.
  • Add a DS1307 RTC for timed switching, or an LDR for automatic night lights.
  • Replace the HC-05 with an ESP8266 module to control the same board over Wi-Fi.

FAQ

Can I use the ATmega32 instead? Yes. The ATmega32 has the same pinout and registers, so change the MCU to atmega32 and rebuild.

Why a voltage divider on HC-05 RXD? The HC-05 logic runs at 3.3 V. The 1 kΩ and 2 kΩ divider lowers the 5 V TX signal from the ATmega16 to about 3.3 V so the module is not stressed.

Does it need internet? No. Bluetooth works directly between the phone and the board within about 10 metres.

ATmega16 Temperature Controller with LM35, 16×2 LCD & Fan Relay

Wiring diagram of an ATmega16 temperature controller with an LM35 sensor, 16x2 LCD, relay-driven cooling fan, status LED, buzzer and 7805 power supply

Build an ATmega16 temperature controller with an LM35 sensor, 16×2 LCD, relay-driven fan and alarm. Wiring table, diagram, fuses and full AVR C code.

  • DifficultyIntermediate
  • Build time2–4 hours
  • Board / MCUATmega16
  • Parts14 items
  • CodeAVR C

Need it ready-made? Buy Ready Project

This ATmega16 temperature controller reads an LM35 sensor, shows the temperature on a 16×2 LCD, and switches a 12 V cooling fan through a relay when it gets too warm. If the temperature keeps rising past a second limit, a red LED and buzzer warn you. It is a practical project for a cabinet, an inverter box, an incubator or a small server shelf.

It is a medium-level build. You use the ATmega16’s built-in 10-bit ADC, drive an HD44780 LCD in 4-bit mode without any library, and write a simple control loop with hysteresis, all in plain AVR C.

How the ATmega16 Temperature Controller Works

  • Sensing: the LM35 gives 10 mV per °C, so 30 °C is 0.30 V. Its output goes to PA0 (ADC0).
  • Measuring: the ADC uses the ATmega16’s internal 2.56 V reference. Each ADC step is 2.5 mV, which is 0.25 °C. The code averages 16 readings to remove noise.
  • Fan control with hysteresis: the fan relay on PC7 turns on at 35 °C and stays on until the temperature falls to 32 °C. The 3 °C gap stops the relay chattering on and off around one value.
  • Alarm: at 45 °C the LED on PD7 and the buzzer on PD6 blink, and the LCD shows ALARM!.
  • Display: line 1 shows the temperature to 0.1 °C, line 2 shows the fan state and the set point.

One ATmega16 detail matters here: PC2–PC5 are also the JTAG pins, and JTAG is on from the factory. The code writes the JTD bit twice at start-up to turn JTAG off, and the fuse values below also disable it, so the LCD data lines work normally.

Components Required

  • ATmega16 or ATmega16A microcontroller (DIP-40) – 1
  • 16 MHz crystal – 1, with 22 pF ceramic capacitors – 2
  • LM35 temperature sensor (TO-92) – 1
  • 16×2 character LCD (HD44780 compatible) – 1
  • 10 kΩ potentiometer for LCD contrast – 1
  • 1-channel 5 V relay module – 1
  • 12 V DC cooling fan – 1
  • Active 5 V buzzer – 1
  • Red LED – 1, with 330 Ω resistor – 1
  • 10 kΩ resistor (reset pull-up) – 1, 220 Ω resistor (LCD backlight) – 1
  • 7805 voltage regulator – 1, 10 µF and 100 µF electrolytic capacitors, 100 nF ceramic capacitors – 3
  • 12 V DC adapter (powers the fan and, through the 7805, the 5 V rail)
  • USBasp or another AVR ISP programmer
  • Breadboard or perfboard and jumper wires

Wiring Table (Pin-to-Pin)

PartPart PinATmega16 PinNotes
7805IN / GND / OUT12 V in / GND / 5 V rail10 µF on input, 100 µF + 100 nF on output
ATmega16VCC (10), AVCC (30)5 VAVCC must be connected for the ADC
ATmega16GND (11, 31)GND100 nF between VCC and GND near the chip
ATmega16RESET (9)10 kΩ to 5 VAlso goes to the ISP header
16 MHz crystalBoth legsXTAL1 (13), XTAL2 (12)22 pF from each pin to GND
ATmega16AREF (32)100 nF to GNDDo not tie AREF to 5 V (code uses 2.56 V internal)
LM351 (+Vs)5 VFlat face toward you, pins left to right
LM352 (Vout)PA0 / ADC0 (40)10 mV per °C
LM353 (GND)GND
LCD1 VSS, 5 RW, 16 KGNDRW tied low (write only)
LCD2 VDD5 V
LCD3 V010 kΩ pot wiperPot ends to 5 V and GND
LCD4 RSPC0 (22)
LCD6 EPC1 (23)
LCD11–14 D4–D7PC2–PC5 (24–27)JTAG pins, disabled in code and fuses
LCD15 A5 V through 220 ΩBacklight
Relay moduleIN / VCC / GNDPC7 (29) / 5 V / GNDUsually active-low
Relay contactsCOM / NO12 V + / fan +Fan − to 12 V −
Buzzer+ / −PD6 (20) / GNDActive buzzer, under 20 mA
LEDAnode / cathodePD7 (21) via 330 Ω / GNDAlarm indicator

Connection Diagram

The illustration below is also the featured image and gives an overview of the build. Use the pin-accurate drawing under it, which matches the wiring table, when you connect the parts.

Wiring diagram of an ATmega16 temperature controller with an LM35 sensor, 16x2 LCD, relay-driven cooling fan, status LED, buzzer and 7805 power supply
ATmega16 temperature controller overview: LM35, 16×2 LCD, relay and fan, LED, buzzer and 7805 supply.
ATmega16 Temperature Controller – Wiring ATmega16 (DIP-40) PA0/ADC0 (40) AREF (32) VCC (10), AVCC (30) GND (11, 31) RESET (9) XTAL1 (13), XTAL2 (12) PC0 (22) RS PC1 (23) E PC2–PC5 (24–27) D4–D7 PC7 (29) relay PD6 (20) buzzer PD7 (21) LED LM35 (flat face front) Pin 1 +Vs → 5 V Pin 2 Vout → PA0 Pin 3 GND → GND AREF 100 nF→GND RESET: 10 kΩ to 5 V 16 MHz crystal XTAL1–XTAL2 22 pF from each XTAL pin to GND 100 nF VCC–GND near chip 16×2 LCD (HD44780) Temp: 31.5 CFan:ON Set:35 1 VSS→GND, 2 VDD→5V, 3 V0→10k pot wiper 4 RS→PC0, 5 RW→GND, 6 E→PC1 11–14 D4–D7→PC2–PC5, 15 A→5V(220Ω), 16 K→GND 5 V Relay Module + 12 V Fan IN→PC7, VCC→5V, GND→GND 12 V + → COM, NO → fan + fan − → 12 V − PD6 → active 5 V buzzer (+), buzzer (−) → GND PD7 → 330 Ω → red LED anode, cathode → GND 7805 supply: 9–12 V in → 7805 → 5 V rail 10 µF on input, 100 µF + 100 nF on output; all grounds common Yellow = sensor signal, green = LCD bus, blue = relay, orange = alarm outputs, red = power. Pin numbers are for the DIP-40 package.
Pin-accurate connection diagram: LM35 on PA0, LCD on PC0–PC5, relay on PC7, buzzer on PD6 and LED on PD7.

ATmega16 Code (AVR-GCC)

Create a new GCC C project for the ATmega16 in Microchip Studio, or save the file as main.c if you use avr-gcc from the command line. No external libraries are needed. You can change the fan and alarm temperatures at the top of the file.

/*
  ATmega16 Temperature Controller
  LM35 sensor + 16x2 LCD (4-bit) + relay-driven fan + LED and buzzer alarm
  Compiler : AVR-GCC (Microchip Studio, or avr-gcc + avrdude)
  Clock    : 16 MHz external crystal  (fuses: lfuse 0xFF, hfuse 0xD9)

  Wiring
    LM35 Vout -> PA0 (ADC0)    AREF -> 100 nF -> GND    AVCC -> 5 V
    LCD RS -> PC0   E -> PC1   D4..D7 -> PC2..PC5   RW -> GND
    Relay IN -> PC7            Buzzer -> PD6         LED -> PD7 (330 ohm)
*/

#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <stdio.h>

// ---- user settings (temperatures in tenths of a degree C) ----
#define FAN_ON_X10     350   // fan turns ON at 35.0 C
#define FAN_OFF_X10    320   // fan turns OFF at 32.0 C (3 C hysteresis)
#define ALARM_X10      450   // buzzer + LED alarm at 45.0 C
#define RELAY_ACTIVE_LOW 1   // most blue relay modules switch ON when IN is LOW

// ---- LCD pins on PORTC ----
#define LCD_RS PC0
#define LCD_E  PC1
// D4..D7 are PC2..PC5

#define RELAY_PIN  PC7
#define BUZZER_PIN PD6
#define LED_PIN    PD7

// Send the low 4 bits of n to D4..D7 and pulse E
static void lcd_nibble(uint8_t n) {
  PORTC = (PORTC & 0xC3) | ((n & 0x0F) << 2);   // keep PC0, PC1, PC6, PC7
  PORTC |= (1 << LCD_E);
  _delay_us(1);
  PORTC &= ~(1 << LCD_E);
  _delay_us(50);
}

static void lcd_send(uint8_t value, uint8_t is_data) {
  if (is_data) PORTC |= (1 << LCD_RS); else PORTC &= ~(1 << LCD_RS);
  lcd_nibble(value >> 4);
  lcd_nibble(value);
  if (!is_data && value < 4) _delay_ms(2);        // clear / home are slow
}

static void lcd_cmd(uint8_t c)  { lcd_send(c, 0); }
static void lcd_char(char c)    { lcd_send((uint8_t)c, 1); }
static void lcd_print(const char *s) { while (*s) lcd_char(*s++); }
static void lcd_goto(uint8_t row, uint8_t col) { lcd_cmd(0x80 | (row ? 0x40 : 0x00) | col); }

static void lcd_init(void) {
  _delay_ms(50);                 // wait for LCD power-up
  PORTC &= ~(1 << LCD_RS);
  lcd_nibble(0x03); _delay_ms(5);
  lcd_nibble(0x03); _delay_ms(1);
  lcd_nibble(0x03);
  lcd_nibble(0x02);              // switch to 4-bit mode
  lcd_cmd(0x28);                 // 4-bit, 2 lines, 5x8 font
  lcd_cmd(0x0C);                 // display on, cursor off
  lcd_cmd(0x06);                 // auto-increment
  lcd_cmd(0x01);                 // clear
}

// ADC with the internal 2.56 V reference: 1 step = 2.5 mV = 0.25 C for the LM35
static void adc_init(void) {
  ADMUX  = (1 << REFS1) | (1 << REFS0);                               // 2.56 V ref, channel ADC0
  ADCSRA = (1 << ADEN) | (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);  // enable, 16 MHz / 128 = 125 kHz
}

static uint16_t adc_read(void) {
  ADCSRA |= (1 << ADSC);
  while (ADCSRA & (1 << ADSC)) { }
  return ADC;
}

// Average 16 readings and convert to tenths of a degree C
static int16_t read_temp_x10(void) {
  uint32_t sum = 0;
  for (uint8_t i = 0; i < 16; i++) { sum += adc_read(); _delay_ms(2); }
  // temp_x10 = adc * 2.5 mV / 10 mV per C * 10  = adc * 2.5
  return (int16_t)((sum * 25UL) / 160UL);
}

static void set_relay(uint8_t on) {
  uint8_t high = RELAY_ACTIVE_LOW ? !on : on;
  if (high) PORTC |= (1 << RELAY_PIN); else PORTC &= ~(1 << RELAY_PIN);
}

int main(void) {
  // PC2..PC5 are JTAG pins on the ATmega16. Turn JTAG off in software
  // (JTD must be written twice within 4 clock cycles) so the LCD can use them.
  uint8_t m = MCUCSR | (1 << JTD);
  MCUCSR = m;
  MCUCSR = m;

  // Relay off level first, then make the pins outputs (no click at power-up)
  set_relay(0);
  DDRC = 0xFF;                                   // LCD + relay
  DDRD |= (1 << BUZZER_PIN) | (1 << LED_PIN);
  PORTD &= ~((1 << BUZZER_PIN) | (1 << LED_PIN));

  lcd_init();
  adc_init();
  lcd_print(" ATmega16 Temp ");
  lcd_goto(1, 0);
  lcd_print("  Controller   ");
  _delay_ms(1500);
  lcd_cmd(0x01);

  uint8_t fan_on = 0;
  uint8_t blink = 0;
  char line[17];

  while (1) {
    int16_t t = read_temp_x10();

    // Fan control with hysteresis
    if (!fan_on && t >= FAN_ON_X10)  fan_on = 1;
    if (fan_on  && t <= FAN_OFF_X10) fan_on = 0;
    set_relay(fan_on);

    // Over-temperature alarm: LED and buzzer blink together
    uint8_t alarm = (t >= ALARM_X10);
    blink ^= 1;
    if (alarm && blink) PORTD |= (1 << BUZZER_PIN) | (1 << LED_PIN);
    else                PORTD &= ~((1 << BUZZER_PIN) | (1 << LED_PIN));

    // Line 1: temperature
    snprintf(line, sizeof(line), "Temp:%3d.%d C    ", t / 10, t % 10);
    lcd_goto(0, 0); lcd_print(line);
    // Line 2: fan state and set point (or ALARM)
    if (alarm) snprintf(line, sizeof(line), "Fan:ON  ALARM!  ");
    else       snprintf(line, sizeof(line), "Fan:%s Set:%2d  ", fan_on ? "ON " : "OFF", FAN_ON_X10 / 10);
    lcd_goto(1, 0); lcd_print(line);

    _delay_ms(400);
  }
}

Compile, Set Fuses and Upload

A new ATmega16 runs from its internal 1 MHz oscillator with JTAG enabled. Set the fuses once so it uses the 16 MHz crystal and frees PORTC. With a USBasp and avrdude:

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:0xFF:m -U hfuse:w:0xD9:m
avrdude -c usbasp -p m16 -U flash:w:main.hex:i

Connect the crystal before writing the fuses. If the fuse is set to an external crystal and none is fitted, the chip will not respond to the programmer until you give it a clock.

Testing and Calibration

  1. Power the board and turn the contrast pot until the LCD text is clear.
  2. Check the room temperature on the LCD against a known thermometer. The LM35 is usually within ±0.5 °C at room temperature.
  3. Warm the LM35 gently with your fingers or a hair dryer on low. At 35 °C the relay should click and the fan should start.
  4. Let it cool. The fan should stop at 32 °C, not at 34.9 °C, which shows the hysteresis is working.
  5. Heat it carefully past 45 °C to check that the LED, buzzer and ALARM! message work.

Troubleshooting

ProblemFix
LCD shows only black boxesAdjust the contrast pot. If it still shows boxes, check RS, E and D4–D7, and confirm JTAG is off (hfuse 0xD9).
LCD shows random charactersThe clock is wrong, so the delays are wrong. Check the crystal, the 22 pF capacitors and lfuse 0xFF.
Temperature reads 0 or jumps wildlyConnect AVCC (pin 30) to 5 V and fit the 100 nF capacitor on AREF. Keep the LM35 wire short or use shielded cable.
Temperature reads far too highAREF is probably tied to 5 V. Remove that link; the internal 2.56 V reference needs AREF free with only a capacitor.
Fan works the wrong way roundYour relay module is active-high. Set RELAY_ACTIVE_LOW to 0.
Chip resets when the relay clicksAdd a 100 µF capacitor on the 5 V rail and keep fan wires away from the LM35 and the reset line.

Ideas to Extend This Project

  • Add two push-buttons on PD2 and PD3 to change the set point, and save it in EEPROM.
  • Replace the relay with a logic-level MOSFET and use PWM on OC1A (PD5) for variable fan speed.
  • Add a second LM35 on PA1 to compare inside and outside temperature.
  • Send the readings over the UART (PD0/PD1) to a PC or a Bluetooth module for logging.

FAQ

Can I use an ATmega32 instead? Yes. The ATmega32 has the same pinout and registers for everything used here, so change only the -mmcu and avrdude part names.

Why use the 2.56 V reference and not 5 V? The LM35 output stays under 1.5 V for normal temperatures. A smaller reference gives 0.25 °C steps instead of about 0.5 °C, so the reading is finer.

Can the relay switch a mains fan? The relay contacts may be rated for 250 V AC, but start with a 12 V DC fan. Switch mains only inside a closed, insulated enclosure, and ask a qualified electrician if you are not sure.

Related Projects

Browse more ATmega16 on Arduino Project Hub.

ATmega16 Digital Dice with 7-Segment

ATmega16 digital dice on a breadboard with a single 7-segment display, roll button and resistors

Build a small ATmega16 digital dice with a 7-segment display and one roll button. Includes the wiring table, connection diagram, AVR-GCC code and fuse settings.

  • DifficultyEasy
  • Build time1–2 hours
  • Board / MCUATmega16
  • Parts10 items
  • CodeAVR C

Need it ready-made? Buy Ready Project

ATmega16 digital dice on a breadboard with a single 7-segment display, roll button and resistors

An ATmega16 digital dice is a small, satisfyingfirst project on this 40-pin AVR chip. One push button rolls the die, a single common-cathode 7-segment display flashes through the faces, and when you let go a number from 1 to 6 stays lit. There is no Arduino board in this build: you program the bare ATmega16 (or an ATmega16 development board) in C with avr-gcc or Microchip Studio.

This tutorial gives you the parts list, a pin-to-pin wiring table, a connection diagram, fuse settings for the internal 8 MHz oscillator, and fully commented AVR-GCC code. The circuit uses only PORTA for the display and PD2 for the button, so it is easy to build on a breadboard in one sitting.

How the ATmega16 Digital Dice Works

The seven segments of the display (a through g) are driven by PORTA pins PA0 to PA6. Because the display is common cathode, a logic HIGH on a port pin lights that segment through a 220 Ω resistor. The code stores a bit pattern for each dice face 1 to 6 and writes it to PORTA whenever the face changes.

The ROLL button is wired from PD2 to ground. The pin’s internal pull-up holds it HIGH, so a press reads as LOW. While you hold the button the firmware cycles the display through 1, 2, 3, 4, 5 and 6 about twenty-five times a second, which looks like a rolling die. Timer0 runs freely in the background. When you release the button the firmware mixes the timer count with how long you held the button and maps the result to a face from 1 to 6, so two rolls in a row almost never freeze on the same number by accident.

The ATmega16 runs from its internal 8 MHz RC oscillator, so you do not need an external crystal for this project. You do need to program the low fuse to 0xE4 (internal 8 MHz, CKDIV8 disabled). The factory default is internal 1 MHz, which would make every delay four times too long.

Components Required

  • ATmega16 microcontroller (DIP-40) – 1, or an ATmega16 development board
  • Common-cathode 7-segment display (single digit) – 1
  • Tactile push button – 1 (ROLL)
  • 220 Ω resistors – 7 (one for each segment a–g)
  • 10 kΩ resistor – 1 (RESET pull-up)
  • 100 nF ceramic capacitor – 1 (VCC decoupling)
  • 5 V regulated supply (USB-to-5 V module or a bench supply)
  • Breadboard and jumper wires
  • USBASP, USBtinyISP, or an Arduino Uno used as ISP, plus a 6-pin or 10-pin ISP cable
  • Optional: 16 MHz crystal and 2 × 22 pF capacitors if you prefer an external clock instead of the internal oscillator

Wiring Table (Pin-to-Pin)

ModuleModule PinATmega16 PinNotes
Power+5 VPin 10 (VCC) and pin 30 (AVCC)Always tie AVCC to VCC, even if you are not using the ADC
PowerGNDPin 11 and pin 31 (GND)Connect both ground pins
Decoupling cap100 nFVCC to GNDPlace it close to pins 10 and 11
RESET10 kΩ to +5 VPin 9 (RESET)Keeps the chip out of reset. Do not leave RESET floating
7-segment (CC)Segment aPin 40 (PA0)Through a 220 Ω resistor
7-segment (CC)Segment bPin 39 (PA1)Through a 220 Ω resistor
7-segment (CC)Segment cPin 38 (PA2)Through a 220 Ω resistor
7-segment (CC)Segment dPin 37 (PA3)Through a 220 Ω resistor
7-segment (CC)Segment ePin 36 (PA4)Through a 220 Ω resistor
7-segment (CC)Segment fPin 35 (PA5)Through a 220 Ω resistor
7-segment (CC)Segment gPin 34 (PA6)Through a 220 Ω resistor
7-segment (CC)Common cathodeGNDAll commons on a single-digit display go to ground
ROLL buttonLeg 1Pin 16 (PD2 / INT0)Internal pull-up is enabled in code
ROLL buttonLeg 2GNDPressed = LOW
ISP programmerMISO / MOSI / SCK / RESET / VCC / GNDPin 7 / pin 6 / pin 8 / pin 9 / pin 10 / pin 11PB6, PB5, PB7, RESET. Unplug the programmer after flashing if the wires crowd the breadboard

Use a common-cathode display. A common-anode part will look dark or show inverted garbage because this code drives segments HIGH to turn them on. If your development board already has a reset pull-up and a decoupling capacitor, you do not need to add those two parts again.

Connection Diagram

The wiring diagram below matches the table. Follow the table if any artistic label on the drawing looks crowded: the pin numbers in the table are the ones to trust.

ATmega16 Digital Dice Wiring Wiring diagram: ATmega16 PA0-PA6 drive 7-segment segments a-g through 220 ohm resistors, PD2 to the ROLL button, RESET 10k pull-up, 100nF on VCC. ATmega16 Digital Dice Wiring ATmega16 DIP-40 VCC pin 10 → +5V AVCC pin 30 → +5V GND pins 11 & 31 → GND RESET pin 9 → 10kΩ → +5V PA0 pin 40 → 220Ω → segment a PA1 pin 39 → 220Ω → segment b PA2 pin 38 → 220Ω → segment c PA3 pin 37 → 220Ω → segment d PA4 pin 36 → 220Ω → segment e PA5 pin 35 → 220Ω → segment f PA6 pin 34 → 220Ω → segment g PD2 pin 16 → ROLL button → GND 100nF capacitor between VCC and GND 7-SEGMENT (common cathode) a b c d e f g Common cathode → GND ROLL button PD2 (pin 16) to GND Supply: +5V on VCC and AVCC. Internal 8 MHz oscillator (low fuse 0xE4). No crystal required.
Connection diagram for the ATmega16 digital dice. Match each labelled pin to the wiring table above.

Fuse Settings

Program these fuses once before or after you flash the hex file. The high fuse value 0xD9 disables JTAG so PORTC is free if you later expand the project; SPI programming stays enabled, so you will not lock yourself out.

  • Low fuse = 0xE4 — internal 8 MHz RC oscillator, CKDIV8 disabled, brown-out detector off
  • High fuse = 0xD9 — JTAG disabled, SPIEN enabled

With a USBASP the commands are:

avrdude -c usbasp -p m16 -U lfuse:w:0xE4:m -U hfuse:w:0xD9:m
avrdude -c usbasp -p m16 -U flash:w:atmega16_digital_dice.hex

Complete AVR-GCC Code

Save the file as atmega16_digital_dice.c. Define F_CPU as 8 MHz so _delay_ms() matches the fuse settings above.

/*
 * ATmega16 Digital Dice with a single 7-segment display
 *
 * Press and hold the ROLL button (PD2, active LOW). The display
 * cycles quickly through 1-6 so it looks like a rolling die.
 * When you release the button, a number from 1 to 6 stays on
 * the display. Randomness comes from Timer0 (free-running) mixed
 * with how long the button was held.
 *
 * Hardware assumptions
 * --------------------
 * MCU:        ATmega16, DIP-40
 * Clock:      internal 8 MHz RC oscillator (CKDIV8 disabled)
 * Display:    common-cathode 7-segment, segments a-g on PORTA
 * Button:     PD2 to GND, internal pull-up enabled
 *
 * Fuse bytes (AVRDUDE)
 * --------------------
 * Low  fuse  = 0xE4   // internal 8 MHz, CKDIV8 off, BOD off
 * High fuse  = 0xD9   // JTAG disabled, SPI programming enabled
 *
 *   avrdude -c usbasp -p m16 -U lfuse:w:0xE4:m -U hfuse:w:0xD9:m
 *   avrdude -c usbasp -p m16 -U flash:w:atmega16_digital_dice.hex
 *
 * Build (avr-gcc)
 * ---------------
 *   avr-gcc -mmcu=atmega16 -DF_CPU=8000000UL -Os -o dice.elf atmega16_digital_dice.c
 *   avr-objcopy -O ihex dice.elf atmega16_digital_dice.hex
 *
 * Written for Arduino Project Hub / this tutorial. Public domain.
 */

#define F_CPU 8000000UL

#include <avr/io.h>
#include <util/delay.h>
#include <stdint.h>

/* Segment pins: PA0=a, PA1=b, PA2=c, PA3=d, PA4=e, PA5=f, PA6=g.
 * Common cathode: a 1-bit turns that segment ON.
 * Patterns are for digits 1 to 6 (index 0 is unused).
 */
static const uint8_t DICE_FACE[7] = {
    0x00,       /* 0: blank, never shown as a dice face */
    0b0000110,  /* 1: b + c                         = 0x06 */
    0b1011011,  /* 2: a + b + d + e + g             = 0x5B */
    0b1001111,  /* 3: a + b + c + d + g             = 0x4F */
    0b1100110,  /* 4: b + c + f + g                 = 0x66 */
    0b1101101,  /* 5: a + c + d + f + g             = 0x6D */
    0b1111101   /* 6: a + c + d + e + f + g         = 0x7D */
};

#define ROLL_PIN   PD2
#define DEBOUNCE_MS 20

static void display_init(void)
{
    /* PA0-PA6 are outputs that drive the seven segments. PA7 unused. */
    DDRA  = 0x7F;
    PORTA = 0x00;

    /* PD2 is an input with the internal pull-up so the pin idles HIGH.
     * The roll button shorts PD2 to GND when pressed.
     */
    DDRD  &= ~(1 << ROLL_PIN);
    PORTD |=  (1 << ROLL_PIN);
}

static void show_face(uint8_t value)
{
    if (value >= 1 && value <= 6) {
        PORTA = DICE_FACE[value];
    } else {
        PORTA = 0x00;
    }
}

static uint8_t button_is_pressed(void)
{
    /* Active LOW because of the pull-up. */
    return (PIND & (1 << ROLL_PIN)) == 0;
}

static void timer0_start(void)
{
    /* Timer0 in normal mode, no prescaler, free-running 0..255.
     * We never enable its interrupt; we only read TCNT0 as a
     * fast-changing number to seed the roll.
     */
    TCCR0 = (1 << CS00);
    TCNT0 = 0;
}

/* Mix the hold time with the free-running timer so two rolls
 * in a row almost never land on the same face by accident.
 */
static uint8_t roll_face(uint16_t hold_loops)
{
    uint8_t raw = (uint8_t)(TCNT0 ^ (hold_loops & 0xFF) ^ (hold_loops >> 4));
    return (uint8_t)((raw % 6) + 1);
}

int main(void)
{
    uint8_t  face = 1;
    uint16_t hold_loops;

    display_init();
    timer0_start();
    show_face(face);

    while (1) {
        if (button_is_pressed()) {
            _delay_ms(DEBOUNCE_MS);
            if (!button_is_pressed()) {
                continue;
            }

            /* Animate 1-6 while the button stays down. */
            hold_loops = 0;
            while (button_is_pressed()) {
                hold_loops++;
                show_face((uint8_t)((hold_loops % 6) + 1));
                _delay_ms(40);
            }

            _delay_ms(DEBOUNCE_MS);
            face = roll_face(hold_loops);
            show_face(face);
        }
    }
}

Build it with:

avr-gcc -mmcu=atmega16 -DF_CPU=8000000UL -Os -o dice.elf atmega16_digital_dice.c
avr-objcopy -O ihex dice.elf atmega16_digital_dice.hex

Code Explanation

  • DICE_FACE[] holds the seven-segment patterns for 1 to 6. Bit 0 is segment a (PA0) and bit 6 is segment g (PA6). A 1 means that segment is ON.
  • display_init() sets PA0–PA6 as outputs and enables the pull-up on PD2 so the roll pin idles HIGH.
  • timer0_start() runs Timer0 with no prescaler. The overflow interrupt is never enabled; the code only reads TCNT0 as a fast-changing number.
  • roll_face() XOR-mixes TCNT0 with the button-hold counter and reduces the result modulo 6, then adds 1 so the face is in the range 1–6.
  • The main loop waits for a press, debounces it, animates the faces while the button stays down, debounces the release, then shows the final face.

Step-by-Step Build Instructions

  1. Place the ATmega16 across the centre of the breadboard so the two rows of pins sit on opposite sides. Pin 1 is marked with a notch and a dot.
  2. Connect pin 10 (VCC) and pin 30 (AVCC) to +5 V. Connect pin 11 and pin 31 to ground. Fit the 100 nF capacitor between VCC and GND near the chip.
  3. Fit the 10 kΩ resistor from pin 9 (RESET) to +5 V.
  4. Wire PA0–PA6 (pins 40 down to 34) through seven 220 Ω resistors to segments a–g of the common-cathode display. Connect the display common to ground.
  5. Connect the roll button between pin 16 (PD2) and ground.
  6. Hook up your USBASP (or Arduino-as-ISP) to MOSI, MISO, SCK, RESET, VCC and GND.
  7. Compile the source to a hex file, write the fuses (0xE4 / 0xD9), then flash the hex file.
  8. Remove the programmer if you want a tidier breadboard, apply 5 V, and press ROLL. The display should rattle through 1–6 and freeze on a face when you release the button.

Troubleshooting

ProblemFix
Display stays darkConfirm the part is common cathode, check the 220 Ω resistors, and measure 5 V on VCC and AVCC. A common-anode display will not light with this code.
Wrong or inverted digitsYour segment-to-pin order may differ from a–g on PA0–PA6. Swap those seven wires to match the table, or edit DICE_FACE[].
Button does nothingCheck PD2 (pin 16) to the button and the other leg to GND. The code uses the internal pull-up, so you should measure about 5 V on PD2 when the button is not pressed.
Animation is very slowThe chip is still running at the factory 1 MHz clock. Write low fuse 0xE4 so it runs at 8 MHz.
avrdude cannot talk to the chipCheck MOSI/MISO/SCK/RESET wiring, share ground with the programmer, and make sure RESET is not stuck low. Try -B 8 to slow the ISP clock.
Chip gets warmRemove power at once and look for a reversed display common or a segment wired straight to VCC without a resistor.

Ideas to Extend the Project

  • Add a second 7-segment digit and show two dice at once, using two PORTA/PORTC nibbles or a 74HC595 shift register.
  • Use the ADC on an unused pin as extra randomness by reading a floating analog pin inside roll_face().
  • Drive a small piezo from PB3 (OC0) and play a short beep when the roll lands.
  • Replace the 7-segment display with seven LEDs arranged as a real die face (pips 1 through 6).

Frequently Asked Questions

Can I use an ATmega32 instead of an ATmega16?

Yes. The DIP-40 pinout is the same for the ports used here. Compile with -mmcu=atmega32 and tell avrdude -p m32. Check the ATmega32 fuse map before you write fuses; do not copy the ATmega16 values blindly.

Can I use a common-anode 7-segment display?

Yes, if you invert the patterns (write PORTA = DICE_FACE[value] ^ 0x7F) and connect the common anode to +5 V instead of ground. The 220 Ω resistors stay in series with each segment.

Do I need an external crystal?

No. The internal 8 MHz oscillator is accurate enough for a dice animation and button debounce. Add a 16 MHz crystal on XTAL1/XTAL2 only if you later add time-critical serial communication and want a more precise clock.

Will this compile in Arduino IDE?

Not as an official Arduino board. ATmega16 is not a standard Arduino core target. Use avr-gcc, Microchip Studio, or add a third-party ATmega16 core. The source itself is plain AVR C and does not use the Arduino API.

Can I power it from a 9 V battery?

Not directly. The ATmega16 is a 5 V part in this circuit (it can run from 4.5–5.5 V at 8 MHz). Use a 7805 or another 5 V regulator if your supply is higher than 5.5 V.

Related Projects

Browse more ATmega16 on Arduino Project Hub.