Python:打开随机LED并延迟关闭

时间:2016-02-02 08:12:19

标签: python random raspberry-pi raspbian

我有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毫秒的任意时间点亮后可以关闭,那就更好了。

我是否需要为此进入深度,黑暗的多处理和线程洞穴?

1 个答案:

答案 0 :(得分:1)

我认为你不得不求助于多线程。您可以先制定行动计划,然后再执行。例如:

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)