【发布时间】:2016-04-22 20:56:34
【问题描述】:
我正在 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 前突破?谢谢。
【问题讨论】:
-
如果
wait_for_edge永远不会返回或停止,您将不得不使用线程。看有没有超时参数,没有的话看线程。最终,您将创建一个线程,然后定期检查它,直到您想要的超时,然后如果它超过您的超时窗口,则取消该线程。 pymotw.com/2/threading -
我认为这是我需要去的地方。有一个替代函数:'GPIO.add_event_detect(24, GPIO.RISING, callback=my_callback)' 每当它被执行时,它就会在 my_callback 处执行 routien。我猜这可能包含增量功能?
-
不看答案。它有一个超时参数。检查@natecat 的回答(谢谢)。
标签: python raspberry-pi raspberry-pi2 gpio