Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:一次又一次地打破while循环_Python_Raspberry Pi_Raspberry Pi2_Gpio - Fatal编程技术网

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

Python:一次又一次地打破while循环,python,raspberry-pi,raspberry-pi2,gpio,Python,Raspberry Pi,Raspberry Pi2,Gpio,我正在用python编程一个RPi。我使用“wait for edge”(等待边缘)计算带有两个磁铁的飞轮转速的霍尔传感器输出。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():

我正在用python编程一个RPi。我使用“wait for edge”(等待边缘)计算带有两个磁铁的飞轮转速的霍尔传感器输出。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.")
#导入
将RPi.GPIO导入为GPIO
导入时间
#将GPIO模式设置为BCM
GPIO.setmode(GPIO.BCM)
GPIO.setup(17,GPIO.IN)#霍尔传感器连接到GPIO 17
def rpm():
脉冲=0#复位脉冲计数器
endTime=time.time()+1#在1秒内计算结束时间
while time.time()
当轮子旋转且边缘被触发时,代码工作正常。问题是当轮子停止且边缘未被触发时,while循环从不检查exit子句,程序暂停。我如何保证即使在脉冲=0时,也能在endTime前中断?谢谢。

所以它只会等待这么长时间。例如,这是一个code只需等待1秒就可以跳出循环

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

您还可以使用
(endTime.time())*1000
作为超时,使其等待endTime爆发

如果
wait_for_edge
从未返回或暂停,则必须使用线程。查看它是否有超时参数,如果没有,请查看线程。最终,您将创建一个线程,然后每隔一段时间检查它,直到所需的超时,然后取消l如果线程超过超时窗口,则返回线程。我想这是我需要返回的位置。还有一个替代函数:“GPIO.add\u event\u detect(24,GPIO.RISING,callback=my\u callback)'在我的_回调中,什么操作了routien?我想它可能包含递增函数?不,请看答案。它有一个超时参数。请检查@natecat的答案(谢谢)。很好,工作正常。我现在需要避免它返回1,而不是正确的0,因为超时后它仍然会增加
脉冲
。如果您查看我的链接,它们实际上显示了如何测试是否发生超时或是否检测到边缘的示例。