from machine import Pin, PWM
import time
from lcd import LCD
import apple
import mii
# lcd
lcd = LCD(rs=23, e=19, d4=26, d5=25, d6=33, d7=32)
# buzzer
buzzer = PWM(Pin(22))
buzzer.duty_u16(0)
# buttons
btn1 = Pin(12, Pin.IN, Pin.PULL_UP)
btn2 = Pin(14, Pin.IN, Pin.PULL_UP)
# state
song = 1
playing = False
note_index = 0
last_time = 0
in_gap = False
def get_song():
if song == 1:
return apple.melody, apple.notes, apple.wholenote
else:
return mii.melody, mii.notes, mii.wholenote
def play_note(freq):
if freq == 0:
buzzer.duty_u16(0)
else:
buzzer.freq(freq)
buzzer.duty_u16(30000)
def stop():
buzzer.duty_u16(0)
def show():
lcd.clear()
lcd.write("BAD APPLE" if song == 1 else "MII THEME")
lcd._send(0xC0, 0)
lcd.write("PLAYING" if playing else "PAUSED")
btn1_prev = 1
btn2_prev = 1
show()
while True:
now = time.ticks_ms()
b1 = btn1.value()
b2 = btn2.value()
# play > / pause II
if btn1_prev == 1 and b1 == 0:
playing = not playing
show()
# switch song
if btn2_prev == 1 and b2 == 0:
song = 2 if song == 1 else 1
playing = False
stop()
note_index = 0
show()
btn1_prev = b1
btn2_prev = b2
# music engine
if playing:
melody, notes, wholenote = get_song()
if note_index >= len(melody):
note_index = 0
note = melody[note_index]
duration_type = notes[note_index]
if duration_type > 0:
note_duration = wholenote / duration_type
else:
note_duration = (wholenote / abs(duration_type)) * 1.5
elapsed = time.ticks_diff(now, last_time)
if not in_gap:
if elapsed >= note_duration * 0.9:
stop()
in_gap = True
else:
if elapsed >= note_duration:
note_index += 1
last_time = now
in_gap = False
if note != 0:
play_note(note)
else:
stop()
else:
last_time = now
time.sleep_ms(5)🍎
mii