from time import sleep
from machine import Pin, PWM
# what size steps to take around the colour wheel
OFFSET = 0.0025
# variable to keep track of the hue
h = 0.0
# Initialize the pins as PWM outputs
red = PWM(Pin(9))
green = PWM(Pin(8))
blue = PWM(Pin(7))
# Set the PWM frequency to 1000 Hz (you can adjust this as needed)
red.freq(1000)
green.freq(1000)
blue.freq(1000)
# From CPython Lib/colorsys.py
def hsv_to_rgb(h, s, v):
if s == 0.0:
return v, v, v
i = int(h * 6.0)
f = (h * 6.0) - i
p = v * (1.0 - s)
q = v * (1.0 - s * f)
t = v * (1.0 - s * (1.0 - f))
i = i % 6
if i == 0:
return v, t, p
if i == 1:
return q, v, p
if i == 2:
return p, v, t
if i == 3:
return p, q, v
if i == 4:
return t, p, v
if i == 5: # noqa: RET503
return v, p, q
# functions to calculate PWM duty cycle
def interval_mapping(x, in_min, in_max, out_min, out_max):
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
def color_to_duty(rgb_value):
rgb_value = int(interval_mapping(rgb_value,0,255,0,65535))
return rgb_value
def setColor(redvalue, greenvalue, bluevalue):
# Set the duty cycle for each color channel
red.duty_u16(color_to_duty(redvalue))
green.duty_u16(color_to_duty(greenvalue))
blue.duty_u16(color_to_duty(bluevalue))
while True:
try:
h += OFFSET
# The LED needs to be set using RGB values, so convert HSV to RGB
# using the hsv_to_rgb() function above
r, g, b = [int(255 * c) for c in hsv_to_rgb(h, 1.0, 1.0)]
# Set RGB color to value
setColor(r, g, b)
sleep(0.1) # Wait for 0.1 seconds
except KeyboardInterrupt:
break
setColor(0,0,0)
print("Finished.")Loading
pi-pico-w
pi-pico-w