import time
import board
import pwmio
# Initialize PWM output for the buzzer
buzzer = pwmio.PWMOut(board.GP11, duty_cycle=0, frequency=440, variable_frequency=True)
adjust_duration = 12
# Function to play a tone
def play_tone(frequency, duration):
buzzer.frequency = round(frequency)
buzzer.duty_cycle = 32768 # 50% duty cycle
time.sleep(duration / adjust_duration)
buzzer.duty_cycle = 0 # Turn off the buzzer
time.sleep(0.02) # Pause between notes, even small is faster
# # Base frequencies for the natural and sharp notes
SILENCE = 10
NOTE_C3 = 131
NOTE_C3_SHARP = 138.59
NOTE_D3 = 146.83
NOTE_D3_SHARP = 155.56
NOTE_E3 = 165
NOTE_F3 = 174.61
NOTE_F3_SHARP = 185
NOTE_G3 = 196
NOTE_G3_SHARP = 207.65
NOTE_A3 = 220
NOTE_A3_SHARP = 233.08
NOTE_B3 = 247
NOTE_C4 = 262
NOTE_C4_SHARP = 277.18
NOTE_D4 = 294
NOTE_D4_SHARP = 311.13
NOTE_E4 = 330
NOTE_F4 = 349
NOTE_F4_SHARP = 370
NOTE_G4 = 392
NOTE_G4_SHARP = 415.3
NOTE_A4 = 440
NOTE_A4_SHARP = 466.16
NOTE_B4 = 494
NOTE_C5 = 523
NOTE_C5_SHARP = 554.37
NOTE_D5 = 587.33
NOTE_D5_SHARP = 622.25
NOTE_E5 = 659.25
NOTE_F5 = 698.46
NOTE_F5_SHARP = 739.99
NOTE_G5 = 783.99
NOTE_G5_SHARP = 830.61
NOTE_A5 = 880
NOTE_A5_SHARP = 932.33
NOTE_B5 = 987.77
NOTE_C6 = 1046.5
NOTE_C6_SHARP = 1108.73
NOTE_D6 = 1174.66
NOTE_D6_SHARP = 1244.51
NOTE_E6 = 1318.51
NOTE_F6 = 1396.91
NOTE_F6_SHARP = 1479.98
NOTE_G6 = 1567.98
NOTE_G6_SHARP = 1661.22
NOTE_A6 = 1760
NOTE_A6_SHARP = 1864.66
NOTE_B6 = 1975.53
NOTE_C7 = 2093
NOTE_C7_SHARP = 2217.46
NOTE_D7 = 2349.32
NOTE_D7_SHARP = 2489.02
NOTE_E7 = 2637.02
NOTE_F7 = 2793.83
NOTE_F7_SHARP = 2959.96
NOTE_G7 = 3135.96
NOTE_G7_SHARP = 3322.44
NOTE_A7 = 3520
NOTE_A7_SHARP = 3729.31
NOTE_B7 = 3951.07
# Define the melody - Random
melody = [(NOTE_G3, 1.0),
(NOTE_G3, 1.0),
(SILENCE, 0.5),
(NOTE_C4, 1.0),
(SILENCE, 0.5),
(NOTE_C4, 1.0),
(SILENCE, 0.5),
(NOTE_C4, 1.0),
(NOTE_C4, 1.0),
(NOTE_C4_SHARP, 1.0),
(SILENCE, 0.5),
(NOTE_C4_SHARP, 1.0),
(SILENCE, 0.5),
(NOTE_C4_SHARP, 1.0),
(SILENCE, 0.5),
(NOTE_G3_SHARP, 1.0),
(NOTE_G3_SHARP, 1.0),
(NOTE_A3_SHARP, 1.0),
(NOTE_A3_SHARP, 1.0),
(NOTE_A3_SHARP, 1.0),
(SILENCE, 0.5),
(NOTE_A3_SHARP, 1.0),
(SILENCE, 0.5),
(NOTE_A3_SHARP, 1.0),
(NOTE_A3_SHARP, 1.0),
(NOTE_C4_SHARP, 1.0),
(SILENCE, 0.5),
(NOTE_C4_SHARP, 1.0),
(NOTE_C4_SHARP, 1.0),
(NOTE_A3_SHARP, 1.0),
(SILENCE, 0.5),
(NOTE_C4_SHARP, 1.0),
(SILENCE, 0.5),
]
# Play the melody
for note in melody:
play_tone(note[0], note[1])
print("Melody finished!")