我有 100 个可寻址 LED:连接到 RPi,并且希望它们随机闪烁。
我最初的想法是在启动时创建一个包含 100 个数字的随机列表,然后循环打开它们。一段时间后我想再次将它们关闭。
RGBlist = [100 random numbers 0-99]
for i in RGBlist:
turnOnLED(i)
如何启动第二个循环与第一个循环同时运行?
delay(X ms)
for i in RGBlist:
turnOffLED(i)
我不希望所有 100 个 LED 在一次关闭之前先打开,我希望先打开 LED(x),然后打开 LED(y)、LED(z)、LED(x) ) 关闭,LED(u) 打开,LED(y) 关闭等等。如果它们可以在点亮 100-500 毫秒的任意时间后关闭,那就更好了。
为此我需要进入多重处理和线程的深渊吗?
最佳答案
我认为您不必求助于多线程。你可以先制定行动计划,然后执行。例如:
import random
import time
RGBlist = [random.randint(0, 100) for _ in range(100)]
delay = 1000 # in milliseconds
# Make a todo list.
# Columns are: time, led, on/off
# First add the entries to turn all leds on
todo = [(delay * i, led, True) for i, led in enumerate(RGBlist)]
# Now add the entries to turn them all off at random intervals
todo += [(delay * i + random.randint(100, 500), led, False)
for i, led in enumerate(RGBlist)]
# Sort the list by the first column: time
todo.sort(key=lambda x: x[0])
# Iterate over the list and perform the actions in sequence
for action_time, led, on in todo:
# Wait until it is time to perform the action
delay(action_time - time.time() * 1000) # In milliseconds
# Perform the action
if on:
turnOnLed(led)
else:
turnOffLed(led)
关于Python:打开随机 LED 并延迟关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35148114/