Python:打开随机发光二极管和延迟转动

2024-09-28 05:15:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有100个地址LED:已连接对一个RPi,想让他们随机眨眼。在

我最初的想法是在启动时创建一个包含100个数字的随机列表,然后循环一个接一个地打开它们。过了一段时间后,我想再次关闭它们。在

RGBlist = [100 random numbers 0-99]
for i in RGBlist:
    turnOnLED(i)

如何启动第二个循环与第一个循环同时运行?在

^{pr2}$

我不希望所有的100个LED在一次关闭之前都打开,我希望LED(x)打开,然后LED(y),LED(z),LED(x)关闭,LED(u)打开,LED(y)关闭,等等。如果它们在被点亮100-500毫秒后可以关闭,那就更好了

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


Tags: in列表forled地址数字random线程
1条回答
网友
1楼 · 发布于 2024-09-28 05:15:26

我想你不用多线程了。你可以先制定一个行动计划,然后再执行它。例如:

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)

相关问题 更多 >

    热门问题