// Module Title: Emerging Technologies (SWE6206)
// Assessment Title: Emerging Technologies based Industry Solutions
// Student Name: OLALEYE KEHINDE MOSEBOLATAN
// Student ID:  2320648
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);

const int motionSensorPin = 5;
const int buzzerPin = 26;
const int ledPin = 33;
const int trigPin = 4;
const int echoPin = 2;

void setup() {
  Serial.begin(115200);
  Serial.println("Setup started");

  lcd.init();
  lcd.begin(16, 2);
 
  Serial.println("LCD initialization started");

  delay(1000);  // Delay for LCD initialization
  pinMode(motionSensorPin, INPUT);
  pinMode(buzzerPin, OUTPUT);
  pinMode(ledPin, OUTPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  Serial.println("Setup completed");
}

void handleMotionSensor() {
  int motionState = digitalRead(motionSensorPin);

  if (motionState == HIGH) {
    lcd.clear();
    lcd.print("Motion Detected!");
    Serial.println("Motion Detected");
    digitalWrite(buzzerPin, HIGH);
    digitalWrite(ledPin, HIGH);
    delay(2000); // Buzzer and LED on for 2 seconds
  } else {
    Serial.println("No Motion");
    digitalWrite(buzzerPin, LOW);
    digitalWrite(ledPin, LOW);
    lcd.clear();
    lcd.print("Security System");
  }
}

void handleUltrasonicSensor() {
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = (duration * 0.0343) / 2;

  if (distance < 50) { 
    lcd.setCursor(0, 1);
    lcd.print("Intruder Alert!");
    Serial.println("Intruder Alert!");
    digitalWrite(buzzerPin, HIGH);
    digitalWrite(ledPin, HIGH);
    delay(2000); // Buzzer and LED on for 2 seconds
  } else {
    digitalWrite(buzzerPin, LOW);
    digitalWrite(ledPin, LOW);
    lcd.clear();
    lcd.print("Security System");
  }
}

void loop() {
  Serial.println("Loop iteration started");

  handleMotionSensor();
  handleUltrasonicSensor();

  Serial.println("Loop iteration completed\n");
  delay(2000); 
}
$abcdeabcde151015202530354045505560fghijfghij