如何在python 3的循环内制作一个计数器?

时间:2018-11-05 22:51:30

标签: python python-3.x

我正在研究PIR传感器,以检测人类的活动。这是我当前正在使用的代码下方,我只需要在循环内创建一个计数器即可计算运动次数。提前致谢!!

import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.IN)    # PIR motion sensor
GPIO.setup(3, GPIO.OUT)    #LED output pin
while True:
    i=GPIO.input(11)
    if i==0:               #sensor is LOW
        print "Not Occupied",i
        GPIO.output(3, 0)  #Turn OFF LED
        time.sleep(0.1)
    elif i==1:             # sensor is HIGH
        print "Occupied",i
        GPIO.output(3, 1)  #Turn ON LED
        time.sleep(0.1)

2 个答案:

答案 0 :(得分:0)

您的问题有点令人困惑,但这是您如何设置计数器

counter = 0
while True:
   counter += 1
   i=GPIO.input(11)
   if i==0:                 #sensor is LOW
       print "Not Occupied",i
       GPIO.output(3, 0)  #Turn OFF LED
       time.sleep(0.1)
   elif i==1:               # sensor is HIGH
       print "Occupied",i
       GPIO.output(3, 1)  #Turn ON LED
       time.sleep(0.1)`
   print(counter)

答案 1 :(得分:0)

当我从Raspberry Pi开始时,我只使用RPi.GPIO库,但是现在我只使用gpiozero库。我认为,它比RPi.GPIO

更清晰

这是我使用库gpiozero而不是RPi.GPIO解决您的问题的方法:

from gpiozero import LED, MotionSensor
from signal import pause

pir = MotionSensor(11)
led = LED(3)
motion_counter = 0

def on_motion():
    global motion_counter
    led.on()
    motion_counter += 1
    print(motion_counter)

def on_no_motion():
    led.off()

pir.when_motion = on_motion
pir.when_no_motion = on_no_motion

pause()

有关此出色库的更多信息:https://gpiozero.readthedocs.io/en/stable/