from machine import Pin, PWM
import time
# Frequency for each note in Hertz
note_freq = {
'C4': 262,
'D4': 294,
'E4': 330,
'F4': 349,
'G4': 392,
'A4': 440,
'B4': 494,
'C5': 523,
'D5': 587,
'E5': 659,
'F5': 698,
'G5': 784,
'A5': 880,
'B5': 988,
}
# Song melody and note durations in seconds
# This is a simplified and partial melody from "Last Christmas"
# Each tuple represents (note, duration)
melody = [
('G4', 0.5), ('G4', 0.5), ('G4', 0.5), ('A4', 0.5),
('F4', 0.5), ('E4', 0.5), ('D4', 0.5),
('E4', 0.5), ('G4', 0.5), ('F4', 0.5), ('D4', 0.5),
('C4', 0.5), ('G4', 0.5), ('F4', 0.5), ('D4', 0.5),
('E4', 0.5), ('C5', 0.5), ('A4', 0.5), ('G4', 0.5),
('F4', 0.5), ('D4', 0.5), ('E4', 0.5), ('G4', 0.5),
]
# Setup PWM on a specified pin (e.g., GP15)
buzzer = PWM(Pin(15))
# Play the melody
for note, duration in melody:
freq = note_freq.get(note, 0) # Get frequency for the note
if freq > 0:
buzzer.freq(freq) # Set the frequency
buzzer.duty_u16(32768) # Set duty cycle to 50%
time.sleep(duration) # Play for the specified duration
buzzer.duty_u16(0) # Silence between notes
time.sleep(0.1) # Brief pause between notes
# Turn off the buzzer
buzzer.deinit()