75 lines
2.6 KiB
Python
75 lines
2.6 KiB
Python
import board
|
|
import rotaryio
|
|
import neopixel
|
|
import time
|
|
import digitalio
|
|
import microcontroller
|
|
|
|
num_pixels = 10
|
|
pixels = neopixel.NeoPixel(board.GP5, num_pixels, auto_write=False)
|
|
encoder = rotaryio.IncrementalEncoder(board.GP19, board.GP18)
|
|
button = digitalio.DigitalInOut(board.GP17)
|
|
button.direction = digitalio.Direction.INPUT
|
|
button.pull = digitalio.Pull.UP
|
|
|
|
# Predefined colors and brightness levels
|
|
colors = [
|
|
(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 255),
|
|
(200, 255, 200), (255, 20, 100), (0, 0, 0)
|
|
]
|
|
brightness_levels = [i / 10 for i in range(11)]
|
|
|
|
# Check and initialize non-volatile memory (NVM)
|
|
if len(microcontroller.nvm) < 2:
|
|
microcontroller.nvm = bytearray(2)
|
|
microcontroller.nvm[0] = 8 # Default brightness index
|
|
microcontroller.nvm[1] = 0 # Default color index
|
|
|
|
brightness_index = min(microcontroller.nvm[0], len(brightness_levels) - 1)
|
|
color_index = min(microcontroller.nvm[1], len(colors) - 1)
|
|
|
|
pixels.brightness = brightness_levels[brightness_index]
|
|
pixels.fill(colors[color_index])
|
|
pixels.show()
|
|
|
|
last_encoder_pos = encoder.position
|
|
button_state = False
|
|
|
|
def fade_colors(start_color, end_color, steps=20, delay=0.01):
|
|
"""Smoothly transition between two colors."""
|
|
for step in range(steps + 1):
|
|
ratio = step / steps
|
|
pixels.fill(tuple(
|
|
int(start_color[i] * (1 - ratio) + end_color[i] * ratio) for i in range(3)
|
|
))
|
|
pixels.show()
|
|
time.sleep(delay)
|
|
|
|
while True:
|
|
# Handle encoder movement for brightness adjustment
|
|
enc_pos = encoder.position
|
|
if enc_pos != last_encoder_pos:
|
|
brightness_index = min(max(brightness_index + (enc_pos - last_encoder_pos), 0), len(brightness_levels) - 1)
|
|
pixels.brightness = brightness_levels[brightness_index]
|
|
pixels.show()
|
|
last_encoder_pos = enc_pos
|
|
print(f"Brightness: {brightness_levels[brightness_index]:.2f}")
|
|
|
|
# Handle button press for color change
|
|
if not button.value:
|
|
if not button_state:
|
|
new_color_index = (color_index + 1) % len(colors)
|
|
fade_colors(colors[color_index], colors[new_color_index])
|
|
color_index = new_color_index
|
|
pixels.fill(colors[color_index])
|
|
pixels.show()
|
|
print(f"Selected color: {colors[color_index]}")
|
|
button_state = True # Prevent multiple detections
|
|
else:
|
|
button_state = False # Reset when button is released
|
|
|
|
# Save settings only if they have changed
|
|
if microcontroller.nvm[0] != brightness_index or microcontroller.nvm[1] != color_index:
|
|
microcontroller.nvm[0] = brightness_index
|
|
microcontroller.nvm[1] = color_index
|