繁体   English   中英

Python:一次又一次地打破while循环

[英]Python: Break out of while loop after time

我是python编程RPi。 我正在使用'等待边缘'来计算一个霍尔传感器输出,用于连接两个磁铁的飞轮的RPM。 rpm例程如下:

# Imports
import RPi.GPIO as GPIO
import time

# Set GPIO Mode as BCM
GPIO.setmode(GPIO.BCM)
GPIO.setup(17 , GPIO.IN)         # Hall sensor attached to GPIO 17

def rpm():
    pulse = 0                    # Reset pulse counter
    endTime = time.time()+1      # Calculate end time in 1 second
    while time.time() < endTime: # Loop while time is less than end time
        GPIO.wait_for_edge(17, GPIO.FALLING) # Wait for a falling edge
        pulse += 1               # Increment pulse
    pulse = str((pulse*60)/2)    # Calculate for pulse per minute
    return pulse                 # Return the 'RPM'

if __name__ == "__main__":
    print("You ran this module directly (and did not import it.")
    input("\n\nPress the enter key to exit.")

当车轮旋转并触发边缘时,代码工作正常。 问题是当车轮停止并且没有触发边缘时,while循环从不检查退出子句并且程序停止。 即使脉冲= 0,我如何保证在endTime之外突破? 谢谢。

使用timeout参数,所以它只会等待这么久。 例如,此代码在断开循环之前只等待1秒。

GPIO.wait_for_edge(17, GPIO.FALLING, timeout = 1000)

你也可以使用(endTime-time.time())*1000作为你的超时,让它等到endTime爆发

暂无
暂无

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

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