from machine import Pin,PWM
import neopixel
import utime

PIN  = Pin(19,Pin.IN,Pin.PULL_UP)
buzzer = PWM(Pin(33))
buzzer.duty_u16(0)

RGB_pin = Pin(26, Pin.OUT)
np = neopixel.NeoPixel(RGB_pin, n=6, bpp=3, timing=1)

N=0
motor1 = PWM(Pin(12))
motor2 = PWM(Pin(13))
motor3 = PWM(Pin(14))
motor4 = PWM(Pin(15))
speed = 65535
def motor(A1,A2,B1,B2):
    motor1.duty_u16(A1) 
    motor2.duty_u16(A2) 
    motor3.duty_u16(B1) 
    motor4.duty_u16(B2)
def exec_cmd(key_val):
    if(key_val==0x18):
#         print("Button ^")
        motor(speed,0,speed,0) # Go forward
    elif(key_val==0x08):
#         print("Button <")
        motor(0,speed,speed,0) # Turn left
    elif(key_val==0x5a):
#         print("Button >")
        motor(speed,0,0,speed) # Turn right
    elif(key_val==0x52):
#         print("Button V")
        motor(0,speed,0,speed) # Go back
    elif(key_val==0x45):
#         print("Button 1")
        for n in range(0,6):
            np[n] = (24,68,2)   # light
        np.write()
    elif(key_val==0x46):
#         print("Button 2")
        for n in range(0,6):
            np[n] = (0,0,0)   
        np.write()
    elif(key_val==0x47):     
#         print("Button 3")     buzzer
        buzzer.duty_u16(2000)
        buzzer.freq(587)                
    else:
        motor(0,0,0,0) # Stop
        buzzer.duty_u16(0)
#         print("STOP")        
            
if __name__ == '__main__':    
    while True:
        if PIN.value() == 0:
            count = 0
            while PIN.value() == 0 and count < 200:
                count += 1
                utime.sleep_us(60)
            count = 0
            while PIN.value() == 1 and count < 80:
                count += 1
                utime.sleep_us(60)
            idx = 0
            cnt = 0
            data = [0,0,0,0]
            for i in range(0,32):
                count = 0
                while PIN.value() == 0 and count < 15:
                    count += 1
                    utime.sleep_us(60)
                count = 0
                while PIN.value() == 1 and count < 40:
                    count += 1
                    utime.sleep_us(60)
                if count > 8:
                    data[idx] |= 1<<cnt
                if cnt == 7:
                    cnt = 0
                    idx += 1
                else:
                    cnt += 1
            if data[0]+data[1] == 0xFF and data[2]+data[3] == 0xFF:
                print("Retrieve key: 0x%02x" %data[2])
                N=data[2]
        if PIN.value() == 1:
            motor(0,0,0,0)     # Stop
            buzzer.duty_u16(0)
        else:
            exec_cmd(N)
            print(N)