Friday, May 27, 2022

[SOLVED] PIR Sensors Triggered in Specific Order

Issue

I have two PIR Sensors connected to a Raspberry Pi one used for either side of a doorway in my design.

I am needing help on how I can do something once the sensors are triggered in a particular order.

Lets call the sensors for simplicity A and B.

Since they will be used for room count I would like the count to increase when they are triggered in order AB and decrease when triggered in order BA.

I have tried this code earlier but it failed (I understand there is no roomCount implemented here but I was testing for expected output):

While True:
    if GPIO.input(pir1):
        if GPIO.input(pir2):
            print(“AB”)
   
    if GPIO.input(pir2):
        if GPIO.input(pir1):
            print(“BA”)

This code was constantly giving the output “AB” no matter which order they were triggered.

Any help on this issue would be appreciated.


Solution

I think you might do better with code more like this pseudo-code:

import time

maxWait = 2 #  Longest time (in seconds) to wait for other PIR to trigger

while True:
    if A is triggered:
        endTime = time.time() + maxWait
        while time.time() < endTime:
             if B is triggered:
                  print("AB")
                  # Sleep till the person has fully passed both sensors
                  while A is triggered or B is triggered:
                     sleep(0.1)

    if B is triggered:
        endTime = time.time() + maxWait
        while time.time() < endTime:
             if A is triggered:
                  print("BA")
                  while A is triggered or B is triggered:
                     sleep(0.1)    


Answered By - Mark Setchell
Answer Checked By - Robin (WPSolving Admin)