gpt4 book ai didi

Python - time.sleep 的替代品

转载 作者:太空宇宙 更新时间:2023-11-04 04:46:55 30 4
gpt4 key购买 nike

您好,有 time.sleep 的替代品吗?因为我想让我的 LED 以精确的赫兹数量闪烁,这是因为调用 time.sleep 也需要时间,所以闪烁需要比预期更多的时间。

#!/usr/bin/python
import RPi.GPIO as GPIO
import time
from threading import Thread

GPIO.setmode(GPIO.BOARD)
GPIO.setup(32, GPIO.IN)

def blink(port, hz):
GPIO.setup(port, GPIO.OUT)
while True:
if GPIO.input(32) == 1: //lever activated?
GPIO.output(port, GPIO.HIGH)
time.sleep(0.5/hz)
GPIO.output(port, GPIO.LOW)
time.sleep(0.5/hz)
else:
GPIO.output(port, GPIO.LOW)
#to make it easier to add new LED
def start(port, hz):
Thread(target=blink, args=(port, hz)).start()
#to add LED insert start(GPIOport, Hz)
start(15, 2)
start(16, 4)
start(18, 6)
start(22, 12)
start(29, 24)

最佳答案

为了保持频率,像这样使用 sleep :

time.sleep(desired_time - time.time())

这样小的延迟就不会累积起来。

dtm = time.time()
pulse = 0.5/Hz
while True:
dtm += pulse
time.sleep(dtm - time.time())
# LED ON
dtm += pulse
time.sleep(dtm - time.time())
# LED OFF

如果确切的占空比(即开/关比)不是问题,您可以简化循环:

while True:
time.sleep(pulse)
# LED ON
dtm += 2*pulse
time.sleep(dtm - time.time())
# LED OFF

更新,停止/恢复闪烁,查看评论,presudocode

 pulse = 0.5/Hz
while True:
dtm = time.time()
while input32 == 1:
... blink LEDs ...
while not input32 == 1:
time.sleep(0.1)

关于Python - time.sleep 的替代品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49357063/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com