import us100, machine, neopixel, time
# TODO adjust pin #s to match soldered connections, adjust distance trigger, _thread?
btn=machine.Pin(15, machine.Pin.IN,machine.Pin.PULL_UP)
light=machine.Pin(1,machine.Pin.OUT)
np=neopixel.NeoPixel(machine.Pin(0), 96)
sensor=us100.US100UART(machine.UART(1))

distance=0
position=0
brightness=0.5
def measure():
    global distance
    distance=sensor.distance()
    return distance


def clear():
    for i in range(np.n):
        np[i]=(0,0,0)
    np.write()
    
def fade(): #pick color
    for i in range(0,4 * 256,8):
        for j in range(np.n):
            if (i // 256) % 2 == 0:
                val = i & 0xff
            else:
                val = 255 - (i & 0xff)
            np[j] = (val, val, 0)
        np.write()

#colorcycle, does start over, do only i actually care about that? probably
def wheel(pos):
    if pos < 85:
        return(pos*3,255-pos*3,0)
    elif pos <170:
        pos-=85
        return(255-pos*3,0,pos*3)
    else:
        pos -=170
        return(0,pos*3,255-pos*3)

def loop():
    global position, brightness
    
    for i in range(np.n):
        hue=int(i*(255/np.n)+position)%256
        color=wheel(hue)
        color=tuple(int(val*brightness) for val in color)
        np[(i+position)%np.n]=color
        np.write()
        position=(position +1)% np.n
        time.sleep_ms(66)

def main():
    try:
        measure()
        print(distance)
        time.sleep_ms(25)
    except Exception:
        print("idk, something went wrong man")
        pass
""" 
main loop, hell yeah! throw them built funcs here!
"""

while True:
    
    if btn.value()==0:
        light.off()
        fade()
        clear()
    else:
        light.on()
    
    main()    
    if distance<=250:
        loop()
        main()
    elif distance>=251:
        clear()
        main()
        
        
     