from machine import Pin, PWM
import time
# Define the buzzer pin
buzzer = PWM(Pin(15)) # Use GPIO 15 for the buzzer
# Define LED pins (4 LEDs)
led_pins = [Pin(2, Pin.OUT), Pin(3, Pin.OUT), Pin(4, Pin.OUT), Pin(5, Pin.OUT)]
# Define the melody for Mario theme (frequencies in Hz)
melody = [
262, 262, 392, 262, 523, 494, 0, # C4 C4 G4 C4 C5 B4 (pause)
262, 262, 392, 262, 523, 494, 0, # C4 C4 G4 C4 C5 B4 (pause)
262, 262, 392, 262, 523, 494, 0, # C4 C4 G4 C4 C5 B4 (pause)
392, 392, 349, 330, 349, 0, # G4 G4 F4 E4 F4 (pause)
262, 262, 392, 262, 523, 494, 0, # C4 C4 G4 C4 C5 B4 (pause)
262, 262, 392, 262, 523, 494, 0, # C4 C4 G4 C4 C5 B4 (pause)
262, 262, 392, 262, 523, 494, 0, # C4 C4 G4 C4 C5 B4 (pause)
392, 392, 349, 330, 349, 0 # G4 G4 F4 E4 F4
]
# Define the duration for each note
note_duration = 0.2 # Duration of each note in seconds
pause_duration = 0.05 # Duration of pause between notes
def play_melody():
for note in melody:
buzzer.freq(note)
buzzer.duty_u16(32768) # Set volume (0-65535)
flicker_leds() # Flicker LEDs while playing
time.sleep(note_duration if note != 0 else pause_duration) # Play note or pause
buzzer.duty_u16(0) # Stop sound
def flicker_leds():
for led in led_pins:
led.on() # Turn LED on
time.sleep(0.1) # Keep it on for 100ms
led.off() # Turn LED off
time.sleep(0.1) # Keep it off for 100ms
try:
play_melody()
finally:
buzzer.deinit() # Clean up
for led in led_pins:
led.off() # Ensure all LEDs are turned off