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

标签 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 毫秒的任意时间后关闭,那就更好了。

为此我需要进入多重处理和线程的深渊吗?

最佳答案

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

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/

相关文章:

python - 如何使用嵌套的 for 循环在 python 中打印出以下模式?

python GTK : Scrollable Grid with clickable images

wordpress - 在 WordPress 中,如何在侧边栏小部件中显示自定义帖子类型的单个随机帖子?

javascript - Python 中的 jQuery $.param'ed 字符串解析(应用引擎)

Python MetaTrader5 指标

random - 如何在 Metal 着色器中获取随机数?

python - 如何根据特定条件从 Pandas 数据框中随机选择行?

python - Raspberry Pi 上的 py.test 和 pytest : Differences ?

java - Makefile: fatal error :jni.h:没有这样的文件或目录

python - 使用 Python、FreeTDS 和 pyodbc 从 Raspberry Pi 3 查询 MSSQL server 2012