Python如果循环time.sleep只执行一次

时间:2017-12-05 09:18:13

标签: python

下面的代码是用Python编写的PIR传感器。

它应该做什么

当传感器第一次激活时,它应等待10秒钟,然后继续打印"检测到入侵者"直到传感器= 0.

实际做什么

而不是等待10次,下面的代码在pir传感器跳动时等待10秒。

为什么?

import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.IN)         #Read output from PIR motion sensor
GPIO.setup(3, GPIO.OUT)         #LED output pin
while True:
       i=GPIO.input(11)
       if i==0:                 #When output from motion sensor is LOW
             print "No intruders",i
             GPIO.output(3, 0)  #Turn OFF LED
             time.sleep(0.1)
       elif i==1:               #When output from motion sensor is HIGH
             time.sleep(10)     #This should be only run once when the pir sensor is trigger
             print "Intruder detected",i
             GPIO.output(3, 1)  #Turn ON LED
             time.sleep(0.1)

1 个答案:

答案 0 :(得分:1)

只需记住它是否是triggererd:

import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.IN)         # Read output from PIR motion sensor
GPIO.setup(3, GPIO.OUT)         # LED output pin
wasTriggered = False            # not yet triggered
while True:
       i=GPIO.input(11)
       if i == 0:                          # When output from motion sensor is LOW
             print "No intruders",i
             wasTriggered = False          # reset trigger if True else does nothing
             GPIO.output(3, 0)             # Turn OFF LED
             time.sleep(0.1)
       elif i == 1:                        # When output from motion sensor is HIGH
             if wasTriggered == False:     # already triggered ?
                 time.sleep(10)            # only run once when the pir sensor is trigger
                 print "Intruder detected",i
                 GPIO.output(3, 1)         # Turn ON LED
                 wasTriggered = True       # set was triggered 
             time.sleep(0.1)

这是创造一个"记忆" - 只有当Sensor在引脚11上报告一个0时,它才会重置。您可能希望切换" Led变为红色+输出文本"和周围的睡眠使它更多" snappy" - 意味着它将立即对传感器的变化作出反应,然后暂停10秒而不是暂停10秒,然后切换灯和&打印文本会断开" Act" - >" React"序列