led-rack-panel/code.py

67 lines
2.2 KiB
Python

import board
import rotaryio
import neopixel
import time
import digitalio
num_pixels = 10
pixels = neopixel.NeoPixel(board.GP5, num_pixels)
encoder = rotaryio.IncrementalEncoder(board.GP19, board.GP18)
button = digitalio.DigitalInOut(board.GP17)
button.direction = digitalio.Direction.INPUT
button.pull = digitalio.Pull.UP
button_state = None # Initialize button state to None
lamp_state = True # Initialize lamp state to True (on)
cold_white = (150, 200, 255)
white = (255, 255, 255)
warm_white = (255, 20, 100)
def interpolate_color(encoder_pos):
if encoder_pos <= -25:
return cold_white
elif encoder_pos >= 25:
return warm_white
else:
ratio = (encoder_pos + 25) / 50.0
inverted_ratio = 1.0 - ratio
interpolated_color = tuple(int(cold_white[i] * inverted_ratio + warm_white[i] * ratio) for i in range(3))
return interpolated_color
fading_in_progress = False # Flag to indicate if fading animation is in progress
while True:
enc_pos = encoder.position
enc_pos = min(max(enc_pos, -25), 25)
# Process button press
if not button.value and button_state is None:
button_state = "pressed"
elif button.value and button_state == "pressed":
lamp_state = not lamp_state # Toggle lamp state
button_state = None # Reset button state
fading_in_progress = True # Set flag to indicate fading animation is in progress
# Perform fading animation if lamp state changed
if fading_in_progress:
if lamp_state: # Fade in
for brightness in range(255):
pixels.brightness = brightness / 255.0
time.sleep(0.2/255)
pixels.brightness = 1.0 # Ensure full brightness is set
else: # Fade out
for brightness in range(255, -1, -1):
pixels.brightness = brightness / 255.0
time.sleep(0.2/255)
pixels.brightness = 0.0 # Ensure brightness is completely off
fading_in_progress = False # Reset flag once fading animation is complete
# Calculate and set current color
current_color = interpolate_color(enc_pos)
pixels.fill(current_color)