from machine import Pin, PWM
import time
buzzer = PWM(Pin(15)) # Use GPIO15 for the buzzer
def play_tone(frequency, duration, volume):
"""
Plays a tone on the buzzer.
:param frequency: Pitch of the sound (in Hz)
:param duration: Duration of the sound (in seconds)
:param volume: Loudness (0-100%, mapped to 0-65535 PWM duty cycle)
"""
if frequency > 0:
buzzer.freq(frequency) # Set pitch
duty = int((volume / 100) * 65535) # Convert volume to duty cycle
buzzer.duty_u16(duty) # Set loudness
time.sleep(duration) # Play for given duration
buzzer.duty_u16(0) # Stop sound
else:
buzzer.duty_u16(0) # Silence
notes = [
(262, 0.5, 50), # C4, 50% volume
(294, 0.5, 60), # D4
(330, 0.5, 70), # E4
(349, 0.5, 80), # F4
(392, 0.5, 90), # G4
(440, 0.5, 100), # A4
(494, 0.5, 100), # B4
(523, 1.0, 100), # C5
]
for freq, dur, vol in notes:
play_tone(freq, dur, vol)
time.sleep(0.1) # Short gap between notes
buzzer.deinit()