ATmega16 Mini Piano with 8 Keys, Buzzer & Demo Song

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.

1 thought on “ATmega16 Mini Piano with 8 Keys, Buzzer & Demo Song”

Leave a Comment