import board
import neopixel_spi as neopixel
import time

NUM_PIXELS = 24

# Use board.SPI() for hardware SPI (MOSI = GPIO10, pin 19)
pixels = neopixel.NeoPixel_SPI(board.SPI(), NUM_PIXELS, brightness=0.1, auto_write=False)

def wheel(pos):
    # Generate rainbow colors across 0-255 positions.
    if pos < 85:
        return (255 - pos * 3, pos * 3, 0)
    if pos < 170:
        pos -= 85
        return (0, 255 - pos * 3, pos * 3)
    pos -= 170
    return (pos * 3, 0, 255 - pos * 3)

try:
    while True:
        # Rainbow cycle
        for j in range(255):
            for i in range(NUM_PIXELS):
                rc_index = (i * 256 // NUM_PIXELS) + j
                pixels[i] = wheel(rc_index & 255)
            pixels.show()
            time.sleep(0.02)
except KeyboardInterrupt:
    print("\nCtrl+C detected. Exiting gracefully...")
finally:
    # Cleanup code that always runs
    pixels.fill((0, 0, 0))  # Turn off all LEDs
    pixels.show()
    time.sleep(0.1)  # Give time to send the final command
    print("LED strip turned off. Program exited safely.")
