#include <Wire.h>
#include <LiquidCrystal_I2C.h>
const int trigPin1 = 2;
const int echoPin1 = 3;
const int trigPin2 = 4;
const int echoPin2 = 5;
const int entryLedPin = 6;
const int exitLedPin = 7;
LiquidCrystal_I2C lcd(0x27, 16, 2);
long duration1, duration2;
int distance1, distance2;
int peopleIn = 0;
int peopleOut = 0;
void init() {
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
pinMode(entryLedPin, OUTPUT);
pinMode(exitLedPin, OUTPUT);
lcd.begin();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("In: 0 Out: 0");
}
void loop() {
// Measure distance with sensor 1
digitalWrite(trigPin1, LOW);
delayMicroseconds(2);
digitalWrite(trigPin1, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin1, LOW);
duration1 = pulseIn(echoPin1, HIGH);
distance1 = duration1 * 0.034 / 2;
// Measure distance with sensor 2
digitalWrite(trigPin2, LOW);
delayMicroseconds(2);
digitalWrite(trigPin2, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin2, LOW);
duration2 = pulseIn(echoPin2, HIGH);
distance2 = duration2 * 0.034 / 2;
// Threshold distance for detecting entry/exit (e.g., 50 cm)
int threshold = 50;
// Detect if someone enters (sensor 1 triggered before sensor 2)
if (distance1 < threshold && distance2 >= threshold) {
delay(500); // delay to debounce and confirm
if (distance1 < threshold && distance2 >= threshold) { // double check
peopleIn++;
digitalWrite(entryLedPin, HIGH); // turn on green LED
delay(200); // LED on duration
digitalWrite(entryLedPin, LOW); // turn off green LED
lcd.setCursor(0, 0);
lcd.print("In: ");
lcd.print(peopleIn);
lcd.print(" Out: ");
lcd.print(peopleOut);
}
}
// Detect if someone exits (sensor 2 triggered before sensor 1)
if (distance2 < threshold && distance1 >= threshold) {
delay(500); // delay to debounce and confirm
if (distance2 < threshold && distance1 >= threshold) { // double check
peopleOut++;
digitalWrite(exitLedPin, HIGH); // turn on red LED
delay(200); // LED on duration
digitalWrite(exitLedPin, LOW); // turn off red LED
lcd.setCursor(0, 0);
lcd.print("In: ");
lcd.print(peopleIn);
lcd.print(" Out: ");
lcd.print(peopleOut);
}
}
delay(100);
}
}