from machine import*
from utime import*
from neopixel import NeoPixel
NUM = 16
NP_PIN = 22
BUZZER_PIN = 14
np = NeoPixel(Pin(NP_PIN), NUM)
NOTES = {
'C3':130.81,'D3':146.83,'E3':164.81,'F3':174.61,'G3':196.00,'A3':220.00,'B3':246.94,
'C4':261.63,'D4':293.66,'E4':329.63,'F4':349.23,'G4':392.00,'A4':440.00,'B4':493.88,
'C5':523.25,'D5':587.33,'E5':659.25,'F5':698.46,'G5':783.99
}
melody = [
('E4',600),('E4',300),('F4',600),('G4',900),
('E4',600),('D4',400),('C4',1200),
('E4',600),('E4',300),('F4',600),('G4',900),
('E4',600),('D4',400),('C4',1200),
('E4',400),('G4',400),('A4',800),
('A4',400),('A4',400),('G4',400),('F4',400),('E4',800),
('E4',400),('G4',400),('A4',800),
('A4',400),('A4',400),('G4',400),('F4',400),('E4',1200),
('C4',600),('D4',400),('E4',800),
('F4',400),('G4',400),('A4',800),
('A4',400),('A4',400),('G4',400),('F4',400),('E4',1200)
]
def wheel(pos):
pos = pos % 256
if pos < 85:
return (pos * 3, 255 - pos * 3, 0)
if pos < 170:
pos -= 85
return (255 - pos * 3, 0, pos * 3)
pos -= 170
return (0, pos * 3, 255 - pos * 3)
def write_wheel(offset):
for i in range(NUM):
np[i] = wheel((offset + int(256 * i / NUM)) % 256)
np.write()
def play_song_and_colors():
b = PWM(Pin(BUZZER_PIN))
b.duty(512)
offset = 0
for note, dur in melody:
freq = NOTES.get(note, 0)
if freq > 0:
b.freq(int(freq))
else:
b.duty(0)
start = ticks_ms()
while ticks_diff(ticks_ms(), start) < dur:
write_wheel(offset)
offset = (offset + 2) % 256
b.duty(400 + (ticks_ms() % 100) // 2)
sleep_ms(20)
if freq > 0:
for d in range(512, 0, -32):
b.duty(d)
sleep_ms(5)
b.deinit()
for i in range(NUM):
np[i] = (0,0,0)
np.write()
if __name__ == '__main__':
play_song_and_colors()