Python:在

时间:2016-04-22 20:56:35

标签: python raspberry-pi raspberry-pi2 gpio

我是一个RPi编程的python。我正在使用'等待边缘'来计算一个霍尔传感器输出,用于连接两个磁铁的飞轮的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之外突破?感谢。

1 个答案:

答案 0 :(得分:3)

use the timeout parameter所以它只会等待这么久。例如,此代码在断开循环之前只等待1秒。

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

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