python - 从 Python 的 for 循环中删除 time.sleep()?
问题描述
我有一些函数通过嵌套的 for 循环驱动 RGB LED,但代码示例使用 time.sleep(),这会阻止我的其余代码运行。我想从 for 循环中删除时间睡眠,但不知道该怎么做。
我做了这个定时器功能,但它不起作用。
currentTime = int(round(time.time() * 1000))
blinkWait = int(round(time.time() * 1000))
def CheckTime( lastTime, wait):
if currentTime - lastTime >= wait:
lastTime += wait
return True
return False
def rainbowCycle(strip, wait_ms=20, iterations=5):
"""Draw rainbow that uniformly distributes itself across all pixels."""
for j in range(256*iterations):
for i in range(strip.numPixels()):
strip.setPixelColor(i, wheel((int(i * 256 / strip.numPixels()) + j) & 255))
if CheckTime(blinkWait,50):
blinkWait = int(round(time.time() * 1000))
strip.show()
我试图实现一个获取当前时间的计时器,然后检查经过的时间,但无法将其集成到 for 循环中。
这些是我想要删除的带有 time.sleep() 的原始示例 LED 模式代码函数。
def rainbowCycle(strip, wait_ms=20, iterations=5):
"""Draw rainbow that uniformly distributes itself across all pixels."""
for j in range(256*iterations):
for i in range(strip.numPixels()):
strip.setPixelColor(i, wheel((int(i * 256 / strip.numPixels()) + j) & 255))
strip.show()
time.sleep(wait_ms/1000.0)
def theaterChaseRainbow(strip, wait_ms=50):
"""Rainbow movie theater light style chaser animation."""
for j in range(256):
for q in range(3):
for i in range(0, strip.numPixels(), 3):
strip.setPixelColor(i+q, wheel((i+j) % 255))
strip.show()
time.sleep(wait_ms/1000.0)
for i in range(0, strip.numPixels(), 3):
strip.setPixelColor(i+q, 0)
先感谢您。
更新
我试图将计时器包装在函数调用周围,但这也不起作用。必须有一种方法可以在 for 循环中的迭代之间实现非阻塞延迟,但我不知所措。
rainbowCycle(strip)
blinkWait = int(round(time.time() * 1000))
更新#2
curr_thread = threading.Thread(target=theaterChaseRainbow, args=(strip))
curr_thread.daemon = False
curr_thread.start()
但我收到此错误“TypeError: TheaterChaseRainbow() argument after * must be an iterable, not Adafruit_NeoPixel”
我还尝试将条带 arg 直接放在函数中。这消除了错误,但没有任何反应。
def theaterChaseRainbow(strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL, LED_STRIP)):
更新#3
在@Aprillion 的建议下,我重新访问了可能重复的帖子。我尽力将这些建议整合到我的代码中。我添加了一个线程如下
def theaterChaseRainbow(strip):
"""Rainbow movie theater light style chaser animation."""
for j in range(256):
for q in range(3):
for i in range(0, strip.numPixels(), 3):
strip.setPixelColor(i+q, wheel((i+j) % 255))
strip.show()
#time.sleep(.05)
for i in range(0, strip.numPixels(), 3):
strip.setPixelColor(i+q, 0)
def myTimer(seconds):
time.sleep(seconds)
theaterChaseRainbow(strip)
然后在主循环中我调用:
myThread = threading.Thread(target=myTimer, args=(.05,))
myThread.start()
这几乎可以工作。它显示并闪烁 LED,但它更加不稳定且不流畅。我认为这是因为它time.sleep
位于嵌套的 for 循环中,而不是整个函数。如何使循环睡眠的第二部分?我将原件time.sleep(.05)
作为注释留在了功能代码中。
解决方案
推荐阅读
- c# - Antlr4 使用 C# - ini 解析器 - 将一个键的值解析为另一个值的键
- python - 使用 PYTHON 运行 Google 数据流模板
- visual-studio - 多次评估 MSBuild 属性
- matlab - 我有频域方程;IFFT如何回到时空域?
- c++ - C ++为类中的枚举项设置值
- postgresql - Postgresql 用户定义函数创建日期或修改日期
- c# - 游戏中改变的变量只在下一场游戏生效
- php - 从 JSON-Array 中完全删除 JSON-Object
- batch-file - 批量重命名文件一个接一个
- c# - 在 UWP 应用中实现搜索功能以从 SQL 服务器中查找数据