from machine import Pin, PWM
from time import sleep
# --- Define the buzzer pin ---
buzzer = PWM(Pin(15))
# --- Define note frequencies (Hz) ---
C = 261
D = 294
E = 329
F = 349
G = 391
A = 440
B = 493
C5 = 523
# --- Define the song (Twinkle Twinkle Little Star) ---
# Format: (note, duration)
song = [
(C, 0.5), (C, 0.5), (G, 0.5), (G, 0.5),
(A, 0.5), (A, 0.5), (G, 1.0),
(F, 0.5), (F, 0.5), (E, 0.5), (E, 0.5),
(D, 0.5), (D, 0.5), (C, 1.0),
(G, 0.5), (G, 0.5), (F, 0.5), (F, 0.5),
(E, 0.5), (E, 0.5), (D, 1.0),
(G, 0.5), (G, 0.5), (F, 0.5), (F, 0.5),
(E, 0.5), (E, 0.5), (D, 1.0),
(C, 0.5), (C, 0.5), (G, 0.5), (G, 0.5),
(A, 0.5), (A, 0.5), (G, 1.0),
(F, 0.5), (F, 0.5), (E, 0.5), (E, 0.5),
(D, 0.5), (D, 0.5), (C, 1.0)
]
# --- Function to play note ---
def play(note, duration):
if note == 0: # rest
buzzer.duty_u16(0)
else:
buzzer.freq(note)
buzzer.duty_u16(30000)
sleep(duration)
buzzer.duty_u16(0)
sleep(0.05) # short pause between notes
# --- Play the song ---
for note, duration in song:
play(note, duration)
# --- Turn off buzzer ---
buzzer.deinit()