7.1. Piano

Short example demonstration video
This project uses 5 pushbuttons and a buzzer to simulate a simple piano where each button plays a different frequency note.
✅
At the end of this example you will learn:
- How to play different tones from buzzer
- How to handle multiple buttons
ℹ️
Parts required:
- Soldered NULA Mini Board
- Breadboard
- 5 x Pushbutton
- Buzzer
- Some jumper wires

Required components
Putting the components together
- Place the buzzer on the breadboard, connect the positive pin on GPIO 2, and other pin to GND.
- For each pushbutton place it on the breadboard, connect one terminal of the button to any free GPIO, and the other terminal to GND.

Components connected together
Code Example
Import necessary modules
from machine import Pin, PWM
import time
Define pins for the buzzer and one for each pushbutton in array.
# Pin configurations
BUZZER_PIN = 2
BUTTON_PINS = [3, 4, 5, 18, 19] # 5 buttons
Declare some common notes and attach them for each button.
# Notes for each button (you can adjust as needed)
NOTES = {
3: 262, # C4
4: 294, # D4
5: 330, # E4
18: 349, # F4
19: 392 # G4
}
Initialize buttons by accessing each one and setting them with PULL_UP configuration.
buttons = {}
for pin_num in BUTTON_PINS:
buttons[pin_num] = Pin(pin_num, Pin.IN, Pin.PULL_UP)
Initialize PWM object for buzzer.
# Setup PWM for buzzer
buzzer = PWM(Pin(BUZZER_PIN))
buzzer.duty(0)
Define functions for playing a single note and muting the buzzer.
# Play note function
def play_note(freq):
buzzer.freq(freq)
buzzer.duty(512) # 50% duty
# Stop buzzer
def stop_note():
buzzer.duty(0)
In the main loop, we go over each button in a for loop and check whether it is pressed, if the button is pressed it plays the given note for that button. If no button is pressed the buzzer is muted.
# Main loop
while True:
pressed_any = False
# Check each button
for pin_num, btn in buttons.items():
if not btn.value(): # Button pressed (active low)
# Get the frequency for the pressed button
freq = NOTES[pin_num]
# Play the note
play_note(freq)
print("PLAY", freq, "Hz")
# Set the flag for pressed button
pressed_any = True
# Exit the loop to avoid multiple notes at once
break
# If no button is pressed, mute the buzzer
if not pressed_any:
stop_note()
# Small delay to avoid overloading the CPU
time.sleep_ms(20)