首页 > 解决方案 > 在 3 种颜色之间随机更改新像素,在每个像素上随机更改

问题描述

所以我目前有 2x 12 像素 Neopixel 环,从 pi 零 W 开始运行。

LED 都按预期工作,通过电平转换器等,并且都按预期反应。

使用python的总菜鸟,但我可以控制像素并让它们做我想做的事,但是我目前想让每个环上的每个像素在随机时间在3种颜色之间随机切换。基本上具有闪烁效果,但仅在该颜色范围内。

目前我只是在一个函数中手动更改每个像素,该函数从我的脚本中调用,循环一定时间。它工作正常,但有点不雅。

def Lights_Flicker():
    
    pixels[0] = (255, 0, 0,0)
    pixels.show()
    time.sleep(.02)
    
    pixels[12] = (255, 0, 0,0)
    pixels.show()
    time.sleep(.02)

    pixels[6] = (122, 100, 0,0)
    pixels.show()
    time.sleep(.02)
    
    pixels[23] = (122, 100, 0,0)
    pixels.show()
    time.sleep(.02)

使用它在函数中循环 x 秒。(播放声音时)

while time.time() < t_end:
            Lights_Flicker()

我对时间部分很满意,它只是颜色闪烁。如果有人知道如何更干净地做到这一点,那就太棒了。

感谢您的关注

标签: pythonraspberry-pineopixel

解决方案


我相信这样的事情应该可以满足您的要求...

from random import randint

colors = [ (255,0,0,0), # put all color tuples here
           (122,100,0,0),
         ]

pixel_num = [ 0, # put all pixels here
              6,
              12,
              23,
            ]

while time.time() <= t_end:
    rand_pixel = randint(0, len(pixel_num)-1)
    rand_color = randint(0, len(colors)-1)

    new_pixel = pixel_num[rand_pixel]
    new_color = colors[rand_color]

    pixels[new_pixel] = new_color
    pixels.show()
    
    time.sleep(0.02)
    
    

推荐阅读