#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);

const int irEntry = 2;
const int irExit = 3;

int peopleCount = 0;

bool lastEntryState = LOW;
bool lastExitState = LOW;

void setup() {
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("People Inside:");
  lcd.setCursor(0, 1);
  lcd.print(peopleCount);

  pinMode(irEntry, INPUT);
  pinMode(irExit, INPUT);

  Serial.begin(9600);
}

void loop() {
  bool currentEntryState = digitalRead(irEntry);
  bool currentExitState = digitalRead(irExit);

  if (currentEntryState == HIGH && lastEntryState == LOW) {
    handleEntry();
  }
  lastEntryState = currentEntryState;

  if (currentExitState == HIGH && lastExitState == LOW) {
    handleExit();
  }
  lastExitState = currentExitState;

  delay(50);
}

void handleEntry() {
  peopleCount++;
  updateLCD();
  Serial.println("Entry detected");
}

void handleExit() {
  if (peopleCount > 0) {
    peopleCount--;
  }
  updateLCD();
  Serial.println("Exit detected");
}

void updateLCD() {
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("People Inside:");
  lcd.setCursor(0, 1);
  lcd.print(peopleCount);
}