# NeoPixels Rainbow on MicroPython
# Updated for dynamic color generation, improved memory efficiency, and added parameterization

from machine import Pin
from neopixel import NeoPixel
from time import sleep

def generate_rainbow():
    """
    Generates a list of RGB values to create a rainbow effect.
    """
    rainbow = []
    for i in range(256):
        if i < 85:
            rainbow.append((i * 3, 255 - i * 3, 0))
        elif i < 170:
            i -= 85
            rainbow.append((255 - i * 3, 0, i * 3))
        else:
            i -= 170
            rainbow.append((0, i * 3, 255 - i * 3))
    return rainbow

def setup_neopixel(pin_num, num_pixels):
    """
    Initializes the NeoPixel ring.
    """
    try:
        pixels = NeoPixel(Pin(pin_num), num_pixels)
        return pixels
    except Exception as e:
        print(f"Error initializing NeoPixel: {e}")
        return None

# Parameterization
PIN_NUM = 11  # Pin number for NeoPixel data line
NUM_PIXELS = 16  # Number of pixels in the NeoPixel ring

rainbow = generate_rainbow()  # Generate rainbow colors dynamically
pixels = setup_neopixel(PIN_NUM, NUM_PIXELS)

if pixels:
    while True:
        rainbow = rainbow[-1:] + rainbow[:-1]  # Rotate colors
        for i in range(NUM_PIXELS):
            pixels[i] = rainbow[i % len(rainbow)]  # Assign color to each pixel
        pixels.write()
        sleep(0.01)