Guides · 7 min read

Arduino Piano With Buttons: 8 Keys, Buzzer, Notes and Recording

Build an Arduino piano with buttons: 8 keys and a passive buzzer, note frequency table, INPUT_PULLUP wiring with no resistors, record and playback, ESP32, Pico.

An Arduino piano with buttons lets you play a scale from C up to the next C by pressing eight keys, and it is one of the favorite projects for anyone starting out in electronics. Each button stands for one note; the Arduino reads which button is pressed and sends a square wave at that note's frequency to a passive buzzer. All you need is an Arduino Uno, eight push buttons, a passive buzzer and a few wires; thanks to INPUT_PULLUP you don't even need a single resistor.

This guide first explains where note frequencies come from and why you need a passive buzzer, then writes a short sketch that maps keys to notes with an array. After that we add octave shifting and the ability to record a melody and play it back, and build the same project on an ESP32 and a Raspberry Pi Pico. At the end you'll find the most common mistakes and ideas for growing your piano.

Buzzer
A piano needs a passive buzzer: it has no oscillator of its own, so it sounds at whatever frequency the Arduino sends.

Parts list for the Arduino piano

  • Arduino Uno (a Nano works with the same pins)
  • 8 push buttons (6×6 mm tactile switches): one per note
  • Passive buzzer, or a small 8 Ω speaker driven by a transistor
  • 3 extra buttons (optional): octave, record and play
  • Breadboard and male-to-male jumper wires
  • USB cable: to power the circuit and upload the code

Why a passive buzzer? An active buzzer can't play notes

Buzzers look alike from the outside, but there are two kinds. An active buzzer has its own oscillator inside; give it voltage and it always beeps at the same pitch (usually around 2–3 kHz), and you can't change its frequency. A passive buzzer is more like a tiny speaker: it vibrates at the frequency of the square wave the Arduino sends with tone(), so it can play any note. An easy way to tell them apart: touch the buzzer across 5 V and GND for a moment; if it beeps continuously it's active, if it only makes a "click" it's passive. Passive models usually show a green circuit board underneath, while active ones are sealed with black epoxy. See What is a buzzer? for more detail.

Note frequencies: the C-D-E chart

In the equal-tempered scale used in Western music, the reference note is A4 = 440 Hz, and each semitone multiplies the frequency by about 1.0595 (the twelfth root of 2). Going up one octave exactly doubles the frequency, going down halves it: middle C (C4) is 262 Hz, while C5 is 523 Hz. You can work out any note with f = 440 × 2^((n − 69) / 12), where n is the note's MIDI number (C4 = 60, A4 = 69). Because tone() takes whole numbers, we round to the nearest hertz; a 1 Hz difference is inaudible.

SolfègeLetterOctave 3 (Hz)Octave 4 (Hz)Octave 5 (Hz)
DoC131262523
ReD147294587
MiE165330659
FaF175349698
SolG196392784
LaA220440880
SiB247494988
To add the black keys too, the sharps in octave 4 are: C# 277 Hz, D# 311 Hz, F# 370 Hz, G# 415 Hz and A# 466 Hz. Just add five more buttons and put these values in the arrays; on the Uno you can use the unused pins A3, A4, A5, D11 and D12.

Wiring: buttons with INPUT_PULLUP and no resistors

The simplest way to wire the buttons is to connect one leg of each button to an Arduino pin, the other leg to GND, and set the pin to INPUT_PULLUP. In this mode the Arduino pulls the pin up to 5 V through an internal resistor of roughly 20–50 kΩ: with the button released the pin reads HIGH, and when pressed it is connected to GND and reads LOW. The logic is inverted, but you don't need a single external resistor and the eight-button circuit goes together in a few minutes. The difference between pull-up and pull-down is explained in What is a pull-up resistor?.

KeyArduino UnoESP32Raspberry Pi Pico
C (262 Hz)D2GPIO 13GP2
D (294 Hz)D3GPIO 14GP3
E (330 Hz)D4GPIO 27GP4
F (349 Hz)D5GPIO 26GP5
G (392 Hz)D6GPIO 33GP6
A (440 Hz)D7GPIO 32GP7
B (494 Hz)D8GPIO 18GP8
High C (523 Hz)D9GPIO 19GP9
Buzzer +D10GPIO 25GP15
Buzzer − and the other leg of every buttonGNDGNDGND
Push button
A 4-leg push button: the legs are joined internally in pairs; diagonal legs always belong to different pairs.
On 4-leg buttons the legs are shorted together in pairs inside. If you're not sure which legs are joined, wire to diagonal legs; they are always in different pairs. Pick the wrong pair and the pin reads as permanently pressed, so the piano plays the same note nonstop.

Mapping keys to notes with an array: the first piano sketch

Instead of writing eight separate if statements, we put the pin numbers and frequencies in two arrays: the key on pin KEY_PINS[i] plays frequency NOTES[i]. Each pass of the loop reads the eight keys in turn, finds the first one pressed and updates the note only when it changes. The basics of arrays are covered in Arduino arrays.

C++ (Arduino IDE)
1// Arduino butonlu piyano / Arduino piano with buttons
2const int BUZZER_PIN = 10;                         // pasif buzzer + / passive buzzer +
3const int KEY_PINS[8] = {2, 3, 4, 5, 6, 7, 8, 9};  // Do Re Mi Fa Sol La Si Do / C D E F G A B C
4const int NOTES[8] = {262, 294, 330, 349, 392, 440, 494, 523};  // Hz, 4. oktav / octave 4
5
6int lastKey = -1;   // son çalan tuş, -1 = sessiz / last key played, -1 = silent
7
8void setup() {
9  for (int i = 0; i < 8; i++) {
10    pinMode(KEY_PINS[i], INPUT_PULLUP);   // dahili direnç, dış direnç yok / internal resistor, no external one
11  }
12}
13
14void loop() {
15  int pressed = -1;
16  for (int i = 0; i < 8; i++) {
17    if (digitalRead(KEY_PINS[i]) == LOW) {   // basılı = LOW / pressed = LOW
18      pressed = i;
19      break;                                 // ilk basılı tuş yeter / first pressed key wins
20    }
21  }
22
23  if (pressed != lastKey) {                  // yalnızca değişince güncelle / update only on change
24    if (pressed >= 0) {
25      tone(BUZZER_PIN, NOTES[pressed]);
26    } else {
27      noTone(BUZZER_PIN);
28    }
29    lastKey = pressed;
30  }
31  delay(5);                                  // kısa bekleme, buton sıçramasını azaltır / short pause against contact bounce
32}

There are two details worth noticing. First, calling tone() again on every loop keeps restarting the timer and makes the sound crackle, so we only call it when the pressed key changes. Second, on the Arduino Uno tone() produces only one sound at a time; if you press two keys together, the one earlier in the list wins. Playing chords like a real piano needs a library that uses several timers or a separate sound module.

Octave shift, record and playback

Now let's add three control buttons. The Octave button shifts the notes up one octave on the first press, down one octave on the next and back to the middle after that; multiplying or dividing the frequency by 2 is all it takes. When you press Record, the Arduino writes every note you play and the silences in between into arrays as frequency and duration, and the built-in LED on D13 stays lit while recording. Stop the recording, press Play, and the melody comes back with the same rhythm. Each event takes 4 bytes, so a 150-event recording uses only 600 bytes of the Uno's 2 KB of RAM. Timing with millis() is explained in Arduino millis() vs delay().

C++ (Arduino IDE)
1// Oktav, kayıt ve çalma özellikli piyano / piano with octave, record and playback
2const int BUZZER_PIN = 10;
3const int LED_PIN = 13;                              // kayıt göstergesi / recording indicator
4const int KEY_PINS[8] = {2, 3, 4, 5, 6, 7, 8, 9};
5const int NOTES[8] = {262, 294, 330, 349, 392, 440, 494, 523};
6const int CTRL_PINS[3] = {A0, A1, A2};               // oktav, kayıt, çal / octave, record, play
7
8const int MAX_EVENTS = 150;
9uint16_t recFreq[MAX_EVENTS];   // 0 = sessizlik / 0 = rest
10uint16_t recDur[MAX_EVENTS];    // süre (ms) / duration (ms)
11int eventCount = 0;
12bool recording = false;
13
14int octaveShift = 0;            // -1, 0, +1
15uint16_t currentFreq = 0;       // şu an çalan frekans / frequency playing now
16unsigned long eventStart = 0;   // olayın başladığı an / when the current event began
17
18int lastCtrl[3] = {HIGH, HIGH, HIGH};
19unsigned long lastPress[3] = {0, 0, 0};
20
21// Kontrol butonuna yeni mi basıldı? (200 ms kilitli) / was a control button just pressed? (200 ms lockout)
22bool justPressed(int i) {
23  int now = digitalRead(CTRL_PINS[i]);
24  bool fell = (lastCtrl[i] == HIGH && now == LOW && millis() - lastPress[i] > 200);
25  lastCtrl[i] = now;
26  if (fell) lastPress[i] = millis();
27  return fell;
28}
29
30uint16_t noteFreq(int key) {
31  uint16_t f = NOTES[key];
32  if (octaveShift > 0) return f * 2;   // bir oktav yukarı / one octave up
33  if (octaveShift < 0) return f / 2;   // bir oktav aşağı / one octave down
34  return f;
35}
36
37// Biten olayı kayda ekle / store the event that just ended
38void saveEvent() {
39  bool leadingRest = (eventCount == 0 && currentFreq == 0);   // baştaki sessizliği atla / skip leading silence
40  if (recording && !leadingRest && eventCount < MAX_EVENTS) {
41    unsigned long d = millis() - eventStart;
42    recFreq[eventCount] = currentFreq;
43    recDur[eventCount] = (d > 60000UL) ? 60000 : d;
44    eventCount++;
45  }
46  eventStart = millis();
47}
48
49void playRecording() {
50  for (int i = 0; i < eventCount; i++) {
51    if (recFreq[i] > 0) tone(BUZZER_PIN, recFreq[i]);
52    else noTone(BUZZER_PIN);
53    delay(recDur[i]);
54  }
55  noTone(BUZZER_PIN);
56  currentFreq = 0;
57}
58
59void setup() {
60  for (int i = 0; i < 8; i++) pinMode(KEY_PINS[i], INPUT_PULLUP);
61  for (int i = 0; i < 3; i++) pinMode(CTRL_PINS[i], INPUT_PULLUP);
62  pinMode(LED_PIN, OUTPUT);
63}
64
65void loop() {
66  if (justPressed(0)) {                              // oktav: 0 -> +1 -> -1 -> 0 / octave cycle
67    octaveShift = (octaveShift == 0) ? 1 : (octaveShift == 1 ? -1 : 0);
68  }
69  if (justPressed(1)) {                              // kayıt aç/kapat / toggle recording
70    if (!recording) {
71      eventCount = 0;
72      recording = true;
73      eventStart = millis();
74    } else {
75      if (currentFreq > 0) saveEvent();              // son notayı kaydet / store the last note
76      recording = false;
77    }
78    digitalWrite(LED_PIN, recording ? HIGH : LOW);
79  }
80  if (justPressed(2) && !recording) {
81    playRecording();
82  }
83
84  uint16_t f = 0;                                    // basılı tuşun frekansı / frequency of the pressed key
85  for (int i = 0; i < 8; i++) {
86    if (digitalRead(KEY_PINS[i]) == LOW) {
87      f = noteFreq(i);
88      break;
89    }
90  }
91  if (f != currentFreq) {                            // nota değişti / note changed
92    saveEvent();
93    currentFreq = f;
94    if (f > 0) tone(BUZZER_PIN, f);
95    else noTone(BUZZER_PIN);
96  }
97  delay(5);
98}
Control buttonArduino Uno pinWhat it does
OctaveA0Normal → one octave up → one octave down → normal
RecordA1First press starts recording (LED on), second press stops it
PlayA2Plays back the recorded melody with the same rhythm
The recording lives in RAM, so it disappears when the Arduino loses power. To keep a melody, write the frequency and duration arrays to EEPROM; the Uno's 1 KB EEPROM holds about 250 events.

Sound quality and volume

tone() produces a square wave with a 50% duty cycle, so the sound is closer to an old game console than a piano. Piezo buzzers resonate around 2–4 kHz, which makes high notes louder than low ones, and notes in octave 3 can sound a little weak. To turn the volume down, put a 100–220 Ω resistor in series with the buzzer. For a fuller, louder sound you can drive a small 8 Ω speaker with a transistor (for example a 2N2222 or BC337); wiring a speaker straight to the pin pulls more current than the pin is rated for and can damage the Arduino.

Button piano with ESP32

On the ESP32 the piano logic is the same; the difference is that the sound comes from the chip's LEDC PWM unit. ledcWriteTone() outputs a 50% duty signal at the requested frequency and goes silent at frequency 0. To make the code compile on both the 2.x and 3.x ESP32 Arduino cores, the LEDC setup is split with a version check. The buttons use pins that have internal pull-ups: GPIO 34–39 are input-only and have no internal pull-ups, so they are not suitable for buttons. Since the ESP32 runs at 3.3 V, the buzzer is a little quieter.

C++ (Arduino IDE)
1// ESP32 butonlu piyano (LEDC) / ESP32 button piano (LEDC)
2const int BUZZER_PIN = 25;
3const int KEY_PINS[8] = {13, 14, 27, 26, 33, 32, 18, 19};   // dahili pull-up'lı pinler / pins with internal pull-ups
4const int NOTES[8] = {262, 294, 330, 349, 392, 440, 494, 523};
5
6#if ESP_ARDUINO_VERSION_MAJOR < 3
7const int BUZZER_CH = 0;     // 2.x çekirdeğinde LEDC kanalı / LEDC channel on core 2.x
8#endif
9
10void playFreq(int freq) {    // 0 = sus / 0 = silence
11#if ESP_ARDUINO_VERSION_MAJOR >= 3
12  ledcWriteTone(BUZZER_PIN, freq);
13#else
14  ledcWriteTone(BUZZER_CH, freq);
15#endif
16}
17
18int lastKey = -1;
19
20void setup() {
21  for (int i = 0; i < 8; i++) pinMode(KEY_PINS[i], INPUT_PULLUP);
22#if ESP_ARDUINO_VERSION_MAJOR >= 3
23  ledcAttach(BUZZER_PIN, 1000, 10);      // pin, başlangıç frekansı, 10 bit / pin, start frequency, 10 bit
24#else
25  ledcSetup(BUZZER_CH, 1000, 10);
26  ledcAttachPin(BUZZER_PIN, BUZZER_CH);
27#endif
28  playFreq(0);
29}
30
31void loop() {
32  int pressed = -1;
33  for (int i = 0; i < 8; i++) {
34    if (digitalRead(KEY_PINS[i]) == LOW) { pressed = i; break; }
35  }
36  if (pressed != lastKey) {
37    playFreq(pressed >= 0 ? NOTES[pressed] : 0);
38    lastKey = pressed;
39  }
40  delay(5);
41}

Piano with Raspberry Pi Pico (MicroPython)

On the Pico, MicroPython's PWM class sets the note frequency with freq() and a 50% duty cycle with duty_u16(32768); setting the duty to 0 silences the buzzer. The buttons use the internal resistor through Pin.PULL_UP and read 0 when pressed. Installing MicroPython on the Pico is covered in What is the Raspberry Pi Pico?.

MicroPython
1from machine import Pin, PWM
2import time
3
4buzzer = PWM(Pin(15))                         # pasif buzzer + / passive buzzer +
5NOTES = [262, 294, 330, 349, 392, 440, 494, 523]
6keys = [Pin(p, Pin.IN, Pin.PULL_UP) for p in range(2, 10)]   # GP2-GP9
7
8last = -1
9while True:
10    pressed = -1
11    for i, key in enumerate(keys):
12        if key.value() == 0:                  # basılı = 0 / pressed = 0
13            pressed = i
14            break
15    if pressed != last:
16        if pressed >= 0:
17            buzzer.freq(NOTES[pressed])
18            buzzer.duty_u16(32768)            # %50 görev / 50% duty
19        else:
20            buzzer.duty_u16(0)                # sus / silence
21        last = pressed
22    time.sleep_ms(5)

Ideas to take your Arduino piano further

  • Lit keys: add an LED next to each button to show the note being played; it makes a great learning toy for kids.
  • Touch piano: replace the buttons with TTP223 touch sensors or the ESP32's touch pins, and cut the keys from aluminum foil.
  • Keypad piano: use a 16-key 4x4 keypad to build a two-octave keyboard with only 8 pins.
  • Demo song mode: add an automatic mode that plays a song stored in arrays when you press a button; keep notes and durations in two separate arrays.
  • Piano with a display: show the name and frequency of the note on an OLED display.
  • Memory game: let the Arduino play a random sequence of notes and repeat it in order; the sequence grows by one note each round.

Common mistakes and fixes

ProblemLikely causeFix
Every key makes the same soundYou are using an active buzzerUse a passive buzzer or a transistor-driven speaker
One note never stopsButton wired to the wrong legs, pin always LOWMove the wires to diagonal legs
No sound when pressing a keyButton's other leg goes to 5V instead of GND, or pinMode is missingWire the other leg to GND and use INPUT_PULLUP
Sound crackles and stutterstone() is called again on every loopUpdate the note only when it changes
Playback rhythm is offDurations were guessed with fixed delay() valuesMeasure durations with millis() differences
analogWrite() stops working on D3 and D11tone() uses Timer2 on the UnoUse D5 or D6 for a PWM LED

A button piano brings together the Arduino basics, arrays, loops, reading inputs and timing, in a single project, which makes it a great learning tool. You'll find more on buttons in How to connect a button to Arduino. The simple buzzer and button piano project in the BlueGrays app has the circuit diagram and code ready step by step; add the octave and recording features from this guide on top of it and grow your own piano.

Frequently asked questions

How do you make a piano with Arduino?

Wire eight buttons between pins D2–D9 and GND and a passive buzzer between D10 and GND. Set the pins to INPUT_PULLUP, read which button is pressed and play that button's note with tone(). Keeping the pin numbers and frequencies in two arrays keeps the code short.

What frequencies do musical notes have for Arduino tone()?

In octave 4, C is 262 Hz, D 294, E 330, F 349, G 392, A 440, B 494 and the next C 523 Hz. Multiply by 2 to go up an octave and divide by 2 to go down.

Active or passive buzzer for an Arduino piano?

Use a passive buzzer. An active buzzer has a built-in oscillator and always beeps at the same pitch, while a passive buzzer sounds at whatever frequency tone() sends, so it can play every note.

Can Arduino play two notes at the same time?

tone() on the Uno drives only one pin at a time, so it can't play chords. Polyphony is possible with libraries that use several timers, with multiple buzzers or with a sound module such as the DFPlayer Mini.

Do I need resistors for Arduino buttons?

Not if you use INPUT_PULLUP: the Arduino switches on an internal 20–50 kΩ pull-up, so no external resistor is needed. The pin then reads LOW while the button is pressed and HIGH when it's released.

How do I make a buzzer louder or quieter?

A 100–220 Ω resistor in series with the buzzer makes it quieter. For more volume, drive an 8 Ω speaker through a transistor; tone() has no software volume control.

See all projects