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

const int pirPin = 2;
const int greenLedPin = 12;
const int redLedPin = 13;
const int buzzerPin = 4;
const int lcdColumns = 21;
const int lcdRows = 22;

LiquidCrystal_I2C lcd(0x27, lcdColumns, lcdRows);
Servo servo;

void setup() {
  pinMode(pirPin, INPUT);
  pinMode(greenLedPin, OUTPUT);
  pinMode(redLedPin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);
  servo.attach(18); // Use the appropriate GPIO pin for your servo
  lcd.init();
  lcd.backlight();
  lcd.print("Anti-Theft System");
  servo.write(0); // Initialize the door as closed
  randomSeed(analogRead(0)); // Seed the random number generator
}

void loop() {
  if (digitalRead(pirPin) == HIGH) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Motion Detected!");
    
    // Simulate person recognition with 50% probability
    if (random(2) == 0) { // 0: No recognition, 1: Recognition
      digitalWrite(redLedPin, HIGH);
      digitalWrite(buzzerPin, HIGH);
      delay(500); // Buzzer on for 0.5 seconds
      digitalWrite(buzzerPin, LOW);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Motion not detected");
      delay(1000); // Delay for clarity
      digitalWrite(redLedPin, LOW);
      servo.write(0); // Lock the "door"
    } else {
      digitalWrite(greenLedPin, HIGH);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Motion Detected");
      delay(1000); // Delay for clarity
      digitalWrite(greenLedPin, LOW);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Door Open");
      servo.write(90); // Unlock the "door"
      delay(5000); // Wait for 5 seconds
      lcd.clear();
      lcd.print("Anti-Theft System");
      servo.write(0); // Lock the "door" again
    }
  }
  delay(100); // Adjust delay based on your simulation needs
}
esp:VIN
esp:GND.2
esp:D13
esp:D12
esp:D14
esp:D27
esp:D26
esp:D25
esp:D33
esp:D32
esp:D35
esp:D34
esp:VN
esp:VP
esp:EN
esp:3V3
esp:GND.1
esp:D15
esp:D2
esp:D4
esp:RX2
esp:TX2
esp:D5
esp:D18
esp:D19
esp:D21
esp:RX0
esp:TX0
esp:D22
esp:D23
pir1:VCC
pir1:OUT
pir1:GND
bz1:1
bz1:2
lcd1:GND
lcd1:VCC
lcd1:SDA
lcd1:SCL
servo1:GND
servo1:V+
servo1:PWM
led1:A
led1:C
led2:A
led2:C
r1:1
r1:2
r2:1
r2:2