Skip to content

Instantly share code, notes, and snippets.

@statico
Created December 22, 2024 20:18
Show Gist options
  • Save statico/3d4ddd1492e997ef58f62825d7c0e7dd to your computer and use it in GitHub Desktop.
Save statico/3d4ddd1492e997ef58f62825d7c0e7dd to your computer and use it in GitHub Desktop.
micropython piano
from machine import Pin, PWM
import time
# Button GPIO pins
button_pins = [5, 18, 19, 21, 22]
# RGB LED GPIO pins
red_pin = 32
green_pin = 33
blue_pin = 25
# Buzzer GPIO pin
buzzer_pin = 13
# Frequencies for C major scale notes
notes = {0: 262, 1: 294, 2: 330, 3: 349, 4: 392} # C4 # D4 # E4 # F4 # G4
# RGB LED colors for each button - yellow, red, blue, green, white
colors = {
0: (255, 255, 0), # Yellow
1: (255, 0, 0), # Red
2: (0, 0, 255), # Blue
3: (0, 255, 0), # Green
4: (255, 255, 255), # White
}
# Initialize buttons
buttons = [Pin(pin, Pin.IN, Pin.PULL_UP) for pin in button_pins]
# Initialize RGB LED
red = PWM(Pin(red_pin), freq=1000, duty=0)
green = PWM(Pin(green_pin), freq=1000, duty=0)
blue = PWM(Pin(blue_pin), freq=1000, duty=0)
# Initialize buzzer
buzzer = PWM(Pin(buzzer_pin))
buzzer.duty(0) # Turn off buzzer initially
def set_rgb_color(r, g, b):
red.duty(int(r / 255 * 1023))
green.duty(int(g / 255 * 1023))
blue.duty(int(b / 255 * 1023))
try:
while True:
for i, button in enumerate(buttons):
if not button.value(): # Button is pressed
buzzer.freq(notes[i])
buzzer.duty(16)
r, g, b = colors[i]
set_rgb_color(r, g, b)
print(f"Button {i} pressed")
while not button.value():
time.sleep(0.1)
print(f"Button {i} released")
buzzer.duty(0)
set_rgb_color(0, 0, 0)
time.sleep(0.1)
except KeyboardInterrupt:
# Cleanup on exit
buzzer.duty(0)
set_rgb_color(0, 0, 0)
red.deinit()
green.deinit()
blue.deinit()
print("Exiting...")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment