# Import necessary libraries for Pico
from machine import Pin, PWM
from time import sleep
# --- Configuration ---
BUZZER_PIN = 13 # Connect your buzzer to GP15 (or another GPIO pin)
PWM_FREQ = 1000 # Base frequency for PWM (adjust if needed)
duty_cycle = 50 # 0-1023 for duty cycle (50% is good)
# --- Define Notes (Frequencies in Hz) ---
# (These are approximate; you might need to fine-tune for a real buzzer)
NOTES = {
'C4': 262, 'D4': 294, 'E4': 330, 'F4': 349, 'G4': 392, 'A4': 440, 'B4': 494,
'C5': 523, 'D5': 587, 'E5': 659, 'F5': 698, 'G5': 784, 'rest': 0 # 0 for silence
}
# --- Melody: Deck the Halls ---
# Format: (Note Name, Duration in seconds) - Durations need adjustment!
deck_the_halls = [
('E4', 0.3), ('D4', 0.3), ('C4', 0.3), ('rest', 0.1), ('D4', 0.3), ('E4', 0.3),
('C4', 0.3), ('rest', 0.1), ('E4', 0.3), ('D4', 0.3), ('C4', 0.3), ('rest', 0.1),
('G4', 0.3), ('F4', 0.15), ('F4', 0.15), ('E4', 0.3), ('rest', 0.1),
# ... (add the rest of the tune here)
]
# --- Setup ---
buzzer = PWM(Pin(BUZZER_PIN))
buzzer.duty_u16(0) # Start silent
def play_note(note_name, duration):
"""Plays a single note on the buzzer."""
frequency = NOTES.get(note_name, 0)
if frequency > 0:
buzzer.freq(frequency)
buzzer.duty_u16(256) # Set duty cycle (e.g., 1/4th power)
sleep(duration)
buzzer.duty_u16(0) # Silence after note
else:
sleep(duration) # Just sleep for rests
# --- Main Loop ---
print("Playing Deck the Halls...")
for note, duration in deck_the_halls:
play_note(note, duration)
sleep(0.05) # Small gap between notes
print("Done!")
buzzer.deinit() # Clean up PWM