简体   繁体   English

Python - time.sleep 的替代品

[英]Python - Alternative to time.sleep

Hello is there a alternative to time.sleep?你好,有没有 time.sleep 的替代品? Because I want to let my LEDs blink in the exact amount of Hz what is not able because to call time.sleep needs time too, so the blinking needs more time than expected.因为我想让我的 LED 以精确的 Hz 数量闪烁,因为调用 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)

To keep the frequency, use sleep like this:要保持频率,请像这样使用睡眠:

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

This way the small delays will not add up.这样小的延迟就不会累加起来。

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

If the exact duty cycle (ie on/off ratio) is not a concern, you could simplify the loop:如果确切的占空比(即开/关比)不是问题,您可以简化循环:

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

UPDATE, stop/resume blinking, see comments, presudocode更新,停止/恢复闪烁,查看评论,presudocode

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

Alternative - time.sleep() 另类time.sleep()

My alternative to time.sleep() would be to use sleep() (shown below): 我对time.sleep()替代方法是使用sleep() (如下所示):

from time import sleep
sleep(0.05)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM