from machine import Pin, PWM
import time
# Define the buzzer pin
buzzer = PWM(Pin(16))
# Dictionary mapping notes to their frequencies
notes = {
'C4': 261,
'D4': 294,
'E4': 329,
'F4': 349,
'G4': 392,
'A4': 440,
'B4': 493,
'C5': 523
}
# Function to play a tone
def play_tone(frequency, duration):
buzzer.freq(frequency)
buzzer.duty_u16(32768) # Set duty cycle to 50%
time.sleep(duration)
buzzer.duty_u16(0) # Turn off the buzzer
# Function to play a melody
def play_melody(melody, tempo):
for note, duration in melody:
if note == 'R': # Rest note
time.sleep(duration * tempo)
else:
play_tone(notes[note], duration * tempo)
time.sleep(0.1 * tempo) # Short pause between notes
# Define a melody (Twinkle Twinkle Little Star)
melody = [
('C4', 0.5), ('C4', 0.5), ('G4', 0.5), ('G4', 0.5),
('A4', 0.5), ('A4', 0.5), ('G4', 1.0),
('F4', 0.5), ('F4', 0.5), ('E4', 0.5), ('E4', 0.5),
('D4', 0.5), ('D4', 0.5), ('C4', 1.0)
]
# Set the tempo (speed of the melody)
tempo = 0.5 # You can adjust this value to make the melody faster or slower
# Play the melody
try:
play_melody(melody, tempo)
except KeyboardInterrupt:
buzzer.deinit() # Clean up the buzzer on exit