import dht
import _thread
from machine import Pin, ADC
from neopixel import NeoPixel
from time import sleep
import random
import time, utime


NUM_LEDS = 16
stop = False
ids = [i for i in range(NUM_LEDS)]

pixels = NeoPixel(Pin(15),NUM_LEDS)
pixels1 = NeoPixel(Pin(21),NUM_LEDS)
gumb = Pin(4, Pin.IN, Pin.PULL_UP)
gumb1 = Pin(19, Pin.IN, Pin.PULL_UP)
sense = dht.DHT22(Pin(5))
pot = ADC(Pin(13, Pin.IN))
a = random.randint(1, NUM_LEDS)
st = 0

def convert(x, in_min, in_max, out_min, out_max):
    return (x - in_min) * (out_max - out_min) // (in_max - in_min) + out_min

def read_sensors():
    speed = convert(pot.read(), 0, 4095, 10, 100)
    sense.measure()
    tempe = sense.temperature()
    color = convert(tempe, -40, 80, 50, 255)

    return round(speed/100, 2), (int(color),0,0)

def check_button():
    global stop
    while True:
        if gumb.value() == 0:
            stop = not stop
            sleep(1)
        sleep(0.01)

def main():
    global stop
    while True:
        if gumb1.value() == 0:
            start = time.time()
            for i in range(5):
                a = random.randint(1, NUM_LEDS)
                pixels1.fill([0,0,0])
                pixels1[a] = [0,250,0]
                pixels1.write()
                poten = convert(pot.read(),0,4096,0,NUM_LEDS)
                time1 = 0
                time2 = 0
                while (time2-time1) <= 0.5:
                    time1 = time.time()
                    st += 1
                    a = random.randint(1, 50)
                    while poten != a:
                        pixels1[poten] = [250,0,0]
                        pixels1.write()
                        print(poten)
                        poten = convert(pot.read(),0,4096,0,NUM_LEDS)
                        pixels1.fill([0,0,0])
                        pixels1[a] = [0,250,0]
                        pixels1.write()
                    time2 = time.time()
            finish = time.time()
            print("Čas: ", end ="")
            print(finish-start,end="")
            print("s")
            print("Število ponovitev", end="")
            print(st)

        for i in ids:
            while stop:
                sleep(0.01)
                continue
            speed, color = read_sensors()
            pixels[i] = (color)
            pixels[i-1] = (0,0,0)
            pixels.write()
            sleep(speed)

        for i in ids[::-1]:
            while stop:
                sleep(0.01)
                continue
            speed, color = read_sensors()
            pixels[i] = (color)
            if i != ids[-1]:
                pixels[i+1] = (0,0,0)
            pixels.write()
            sleep(speed)

t1 = _thread.start_new_thread(main, ())
t2 = _thread.start_new_thread(check_button, ())