from machine import Pin,PWM
import neopixel
import utime

PIN  = Pin(19,Pin.IN,Pin.PULL_UP)
pin = Pin(25, Pin.OUT)
np = neopixel.NeoPixel(pin, n=4, bpp=3, timing=1)
N=0

def exec_cmd(key_val):
    if(key_val==0x45):
#         print("Button 1")
        for i in range(0,4):
            np[i] = (255,0,0)
        np.write()
    elif(key_val==0x46):
#         print("Button 2")
        for i in range(0,4):
            np[i] = (0,255,0)
        np.write()
    elif(key_val==0x47):
#         print("Button 3")
        for i in range(0,4):
            np[i] = (0,0,255)
        np.write()
    elif(key_val==0x44):
#         print("Button 4")
        for i in range(0,4):
            np[i] = (255,255,0)
        np.write()
    elif(key_val==0x40):
#         print("Button 5")
        for i in range(0,4):
            np[i] = (255,0,255)
        np.write()
    elif(key_val==0x43):
#         print("Button 6")
        for i in range(0,4):
            np[i] = (0,255,255)
        np.write()
    elif(key_val==0x07):
#         print("Button 7")
        for i in range(0,4):
            np[i] = (255,255,255)
        np.write()   
            
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]
        exec_cmd(N)
