from machine import Pin
from utime import sleep
from neopixel import NeoPixel
import machine
from machine import ADC
from random import randrange, randint

# Print a message indicating the start of the program
print("Started!")

# Number of LEDs
NUM_LEDS = 16

# Initialize a NeoPixel object with a specified pin and the total number of LEDs
leds = NeoPixel(Pin(15, Pin.OUT), NUM_LEDS)

# Initialize a pin for the potentiometer
potenci = machine.Pin(13, Pin.OUT)
# Initialize an ADC (Analog-to-Digital Converter) for reading values from the potentiometer
adc = ADC(potenci)

# Function for Task 1: Moving white light through LEDs
def vaja1(NUM_LEDS, st=0.1):
    while True:
        for i in range(NUM_LEDS):
            leds[i] = [255, 255, 255]
            leds[i - 1] = [0, 0, 0]
            leds.write()
            # Adjust the sleep duration based on the potentiometer reading
            sleep(adc.read() / 10000)

# Function for Task 2: Changing color randomly with mutation
def vaja2(NUM_LEDS, st=0.1):
    # Initial color
    barva = [randrange(0, 255), randrange(0, 255), randrange(0, 255)]

    while True:
        for i in range(NUM_LEDS):
            # Set the LED color
            leds[i] = barva
            leds.write()

            # Adjust the color with mutation based on the potentiometer reading
            mocMutacije = adc.read() / 150
            mocMutacije = int(mocMutacije)
            
            # Update the color components with random mutations
            r = (barva[0] + randint(-mocMutacije, mocMutacije)) % 256
            g = (barva[1] + randint(-mocMutacije, mocMutacije)) % 256
            b = (barva[2] + randint(-mocMutacije, mocMutacije)) % 256

            # Ensure that the color values stay within the valid RGB range (0-255)
            barva = [r, g, b]
            
            # Introduce a delay before changing to the next LED
            sleep(st)

# Call the second task function with the specified number of LEDs and a shorter sleep duration
vaja2(NUM_LEDS, 0.05)