from machine import Pin,PWM,ADC   
import time
button = Pin(18, Pin.IN)
buzzer = PWM(Pin(33))        
Tone = [0, 392, 440, 494, 523, 587, 659, 698, 784]

QTI_L=Pin(39,Pin.IN,Pin.PULL_UP)
QTI_R=Pin(36,Pin.IN,Pin.PULL_UP)

Song = [ Tone[3], Tone[3], Tone[3], Tone[3], Tone[3], Tone[3],
         Tone[3], Tone[5], Tone[1], Tone[2], Tone[3],
         Tone[4], Tone[4], Tone[4], Tone[4], Tone[4], Tone[3], Tone[3], Tone[3],
         Tone[5], Tone[5], Tone[4], Tone[2], Tone[1], Tone[8] ]

Beat = [ 1, 1, 2, 1, 1, 2,
         1, 1, 1.5, 0.5, 4,
         1, 1, 1, 1, 1, 1, 1, 1,
         1, 1, 1, 1, 2, 2]
def setup():
    buzzer.duty_u16(0)
    
def motor(L12,L13,R14,R15):
    PWM(Pin(12)).duty(L12) 
    PWM(Pin(13)).duty(L13) 
    PWM(Pin(14)).duty(R14) 
    PWM(Pin(15)).duty(R15)

def Tracking():
    QTI_MAX = QTI_L.value() * 2 + QTI_R.value()
    if QTI_MAX == 0:
        motor(800,0,800,0)
    elif QTI_MAX == 1:
        motor(0,800,0,400)
    elif QTI_MAX == 2:
        motor(0,400,0,800)
    elif QTI_MAX == 3:
        motor(0,1000,0,1000)
def loop():
    while button.value() == 1:
        pass
    else:
        while True:
            for i in range(0, len(Song)):
                buzzer.duty_u16(2000)
                buzzer.freq(Song[i])
                for j in range(1, Beat[i] / 0.1):
                    Tracking()
                    time.sleep_ms(25)
                buzzer.duty_u16(0)
                time.sleep(0.01)
                
if __name__ == '__main__':
    setup()
    loop()
