#include <Wire.h>
#include <LiquidCrystal_I2C.h> // Include the LiquidCrystal library for I2C interface
// Constants
const int motionSensorPin = 34;
const int ledPin = 27;
const unsigned long lightDelay = 5000; // Time in milliseconds (5 seconds)
const unsigned long firstThreshold = 3000; // Time in milliseconds (3 seconds)
const unsigned long secondThreshold = 6000; // Time in milliseconds (6 seconds)
const unsigned long thirdThreshold = 10000; // Time in milliseconds (10 seconds)
// Variables
unsigned long lastMotionTime = 0;
bool isLightOn = false;
int percentage = 0;
// LCD module configuration
LiquidCrystal_I2C lcd(0x27, 16, 2); // Set the LCD I2C address to 0x27 and number of columns and rows
void setup() {
pinMode(motionSensorPin, INPUT);
pinMode(ledPin, OUTPUT);
// Initialize the LCD module
Wire.begin();
lcd.begin(16, 2);
lcd.print("Motion Sensor");
lcd.setCursor(0, 1);
lcd.print("Status: OFF");
}
void loop() {
// Check for motion
if (digitalRead(motionSensorPin) == HIGH) {
lastMotionTime = millis();
if (!isLightOn) {
// Turn on the light
digitalWrite(ledPin, HIGH);
isLightOn = true;
// Update LCD display
lcd.setCursor(0, 1);
lcd.print("Status: ON ");
}
}
// Check if the light should turn off
if (isLightOn && millis() - lastMotionTime >= lightDelay) {
// Turn off the light
digitalWrite(ledPin, LOW);
isLightOn = false;
// Update LCD display
lcd.setCursor(0, 1);
lcd.print("Status: OFF");
}
// Check if motion sensor is blocked
if (digitalRead(motionSensorPin) == LOW && isLightOn) {
// Calculate the duration of blocking the sensor
unsigned long duration = millis() - lastMotionTime;
// Determine the percentage based on the duration
if (duration >= thirdThreshold) {
percentage = 100;
} else if (duration >= secondThreshold) {
percentage = 66;
} else if (duration >= firstThreshold) {
percentage = 33;
}
// Update LCD display
lcd.setCursor(0, 0);
lcd.print("Sensor Blocked");
lcd.setCursor(0, 1);
lcd.print(percentage);
lcd.print("% full ");
} else if (!isLightOn) {
// Motion sensor not blocked
lcd.setCursor(0, 0);
lcd.print("No Obstruction ");
lcd.setCursor(0, 1);
lcd.print(" ");
}
}