【问题标题】:Python: Break out of while loop after timePython:一次又一次地跳出while循环
【发布时间】: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


【解决方案1】:

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

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

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

【讨论】:

  • 很好,工作正常。我现在需要避免它返回 1,而不是正确的 0,因为在超时之后它仍然会递增 pulse。
  • 如果您查看我的链接,它们实际上显示了如何测试是否发生超时或检测到边缘的示例。
猜你喜欢
  • 2021-05-22
  • 2015-01-28
  • 2021-08-12
  • 2022-01-06
  • 2015-09-28
  • 2020-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多