how to make a counter inside a loop in python 3?

2685 views python
2

I'm working on PIR sensor in order to detect the movement of human beings. Here is below the code that currently I am using and I just need to make a counter inside the loop in order to count the # of movements. Thanks in advance!!

`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)`

answered question

If you're going to post Python code, you need to reproduce your indentation. Unindented Python code is nonsense.

2 Answers

9

count = 0
for index in range(10):
     count+=1
     #do your work here
print(count)
#should print the number of times the code in the for loop got executed.

posted this
12

Your question is kind of confusing but here is how you would set a counter

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)

posted this

Have an answer?

JD

Please login first before posting an answer.