Python - Alternative to time.sleep

扶醉桌前 提交于 2020-02-04 08:06:15

问题


Hello is there a alternative to 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.

#!/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)

回答1:


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 (i.e. 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

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


来源:https://stackoverflow.com/questions/49357063/python-alternative-to-time-sleep

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!