from machine import Pin,PWM
import neopixel
import random
from time import sleep_ms
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
Time = 500

def exec_cmd(key_val):
    if(key_val==0x18):
#         print("Button ^")
        Time += 50
        if Time > 1000:
            Time = 1000
    elif(key_val==0x52):
#         print("Button v")
        Time -= 50
        if Time < 50:
            Time = 50
    for n in range(0,4):
        np[n] = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
        np.write()
        sleep_ms(Time)
    #for n in range(0,4):
        np[n] = (0,0,0)
        np.write()
        sleep_ms(Time)
            
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)
        
