1 Star 1 Fork 0

Walkline/MicroPython WS2812 Research

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
test_led.py 2.72 KB
一键复制 编辑 原始数据 按行查看 历史
"""
Copyright © 2021 Walkline Wang (https://walkline.wang)
Gitee: https://gitee.com/walkline/micropython-ws2812-research
"""
from machine import Pin
import neopixel
from utime import sleep, time
import urandom
import math
np = neopixel.NeoPixel(Pin(13), 54)
BRIGHT_MAX = 0.6
BRIGHT_MIN = 0.05
BRIGHT_PERCENT = 0
def fill_color(color:int):
global np
np.fill((color, color, color))
np.write()
def clean():
global np
np.fill((0, 0, 0))
np.write()
def show(r, g, b):
global np
for index in range(np.n):
np[index] = (r, g, b)
np.write()
sleep(0.1)
def brightness(percent:int):
if 100 < percent < 0:
percent = 100
percent = percent / 100
return (BRIGHT_MAX - BRIGHT_MIN) * percent + BRIGHT_MIN * percent
def rgb_to_hsv(rgb_color):
"""Converts colors from the RGB color space to the HSV color space.
Parameters
----------
rgb_color : tuple (r, g, b)
Color in the RGB color space
Returns
-------
tuple (h, s, v)
Color in the HSV color space
"""
(r, g, b) = rgb_color
r = float(1 / 255 * r)
g = float(1 / 255 * g)
b = float(1 / 255 * b)
high = max(r, g, b)
low = min(r, g, b)
h, s, v = high, high, high
d = high - low
s = 0 if high == 0 else d/high
if high == low:
h = 0.0
else:
h = {
r: (g - b) / d + (6 if g < b else 0),
g: (b - r) / d + 2,
b: (r - g) / d + 4,
}[high]
h /= 6
return h, s, v
def hsv_to_rgb(hsv_color):
"""Converts colors from the HSV color space to the RGB color space.
Parameters
----------
hsv_color : tuple (h, s, v)
Color in the HSV color space
Returns
-------
tuple (r, g, b)
Color in the RGB color space
"""
(h, s, v) = hsv_color
i = math.floor(h*6)
f = h*6 - i
p = v * (1-s)
q = v * (1-f*s)
t = v * (1-(1-f)*s)
r, g, b = [
(v, t, p),
(q, v, p),
(p, v, t),
(p, q, v),
(t, p, v),
(v, p, q),
][int(i%6)]
r = int(255 * r)
g = int(255 * g)
b = int(255 * b)
return r, g, b
def test_all_color():
r = g = b = 0
color_range = 128
step = 5
for count in range(0, color_range ** 3, step):
b += count
if b > color_range:
b = 0
g += step
if g > color_range:
g = 0
r += step
if r > color_range:
break
show(r, g, b)
def test_random_color():
global np
start = 0
end = 128
BRIGHT_PERCENT = brightness(50)
urandom.seed(time() ** urandom.randint(0, 3000))
for _ in range(100):
for index in range(np.n):
r = urandom.randint(start, end)
g = urandom.randint(start, end)
b = urandom.randint(start, end)
if True:
h, s, v = rgb_to_hsv((r, g, b))
np[index] = hsv_to_rgb((h, s, v * BRIGHT_MAX * 0.5))
else:
np[index] = (int(r * BRIGHT_PERCENT), int(g * BRIGHT_PERCENT), int(b * BRIGHT_PERCENT))
np.write()
if __name__ == '__main__':
clean()
# test_all_color()
test_random_color()
clean()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/walkline/micropython-ws2812-research.git
git@gitee.com:walkline/micropython-ws2812-research.git
walkline
micropython-ws2812-research
MicroPython WS2812 Research
master

搜索帮助