from machine import Pin, PWM
import time
# Define note frequencies (in microseconds for the delay)
C = 2100
D = 1870
E = 1670
f = 1580 # Lowercase f since uppercase F may cause issues
G = 1400
R = 0 # Rest note
# Set up speaker on a PWM pin (e.g., GPIO 2)
speakerOut = PWM(Pin(2))
# Melody and timing
melody = [E, E, E, R,
E, E, E, R,
E, G, C, D, E, R,
f, f, f, f, f, E, E, E, E, D, D, E, D, R, G, R,
E, E, E, R,
E, E, E, R,
E, G, C, D, E, R,
f, f, f, f, f, E, E, E, G, G, f, D, C, R]
MAX_COUNT = len(melody)
# Set overall tempo
tempo = 10000
# Set length of pause between notes
pause = 1000
# Loop variable to increase Rest length
rest_count = 100 # <-BLETCHEROUS HACK; See NOTES
# Function to play a tone
def playTone(tone_, duration):
if tone_ > 0: # if this isn't a Rest beat
elapsed_time = 0
while elapsed_time < duration:
speakerOut.duty(512) # Pulse speaker HIGH
time.sleep_us(tone_ // 2)
speakerOut.duty(0) # Pulse speaker LOW
time.sleep_us(tone_ // 2)
elapsed_time += tone_
else: # Rest beat; loop times delay
for _ in range(rest_count):
time.sleep_us(duration)
# Main loop
while True:
for i in range(MAX_COUNT):
tone_ = melody[i]
beat = 50
duration = beat * tempo # Set up timing
playTone(tone_, duration)
# A pause between notes...
time.sleep_us(pause)