#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define trigPin1 2 // Door sensor
#define echoPin1 3
#define trigPin2 4 // Entry sensor
#define echoPin2 5
#define trigPin3 6 // Exit sensor
#define echoPin3 7
int count = 0; // People counter
bool gateOpen = false; // Track if the gate is open
bool personDetected = false; // Track if a person passed
LiquidCrystal_I2C lcd(0x27, 16, 2);
const int debounceThreshold = 3;
void setup() {
Serial.begin(9600);
lcd.init();
lcd.backlight();
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
pinMode(trigPin3, OUTPUT);
pinMode(echoPin3, INPUT);
}
void loop() {
gateOpen = isConsistentReading(trigPin1, echoPin1, 10);
if (gateOpen && !personDetected) {
Serial.println("Door Open. Checking for person...");
bool entryDetected = isConsistentReading(trigPin2, echoPin2, 30);
bool exitDetected = isConsistentReading(trigPin3, echoPin3, 30);
if (entryDetected && exitDetected) {
Serial.println("Both sensors triggered. No change in count.");
} else if (entryDetected) {
count += 1;
personDetected = true;
Serial.println("Entry detected. Count incremented.");
} else if (exitDetected && count > 0) {
count -= 1;
personDetected = true;
Serial.println("Exit detected. Count decremented.");
}
}
if (!gateOpen && personDetected) {
personDetected = false;
Serial.println("Door Closed. Ready for next person.");
}
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Count: ");
lcd.print(count);
Serial.print("Count: ");
Serial.println(count);
delay(500);
}
bool isConsistentReading(int trigPin, int echoPin, int maxDistance) {
int consistentCount = 0;
for (int i = 0; i < debounceThreshold; i++) {
int distance = getDistance(trigPin, echoPin);
if (distance <= maxDistance) {
consistentCount++;
}
delay(50);
}
return (consistentCount >= debounceThreshold);
}
int getDistance(int trigPin, int echoPin) {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2.0) / 29.1;
return distance;
}