#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Define the LCD
LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C address 0x27, 16x2 display
// Define pins for the LEDs and light sensor
const int greenLedPin = 10;
const int redLedPin = 9;
const int lightSensorPin = 2; // Connected to D0 of LM393 module
// Variables to track the state and time
bool isLightOn = false;
unsigned long lightOnStartTime = 0;
void setup() {
// Initialize the LCD
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Light Off");
// Set up the LED pins
pinMode(greenLedPin, OUTPUT);
pinMode(redLedPin, OUTPUT);
// Set up the light sensor pin
pinMode(lightSensorPin, INPUT_PULLUP);
// Start with LEDs off
digitalWrite(greenLedPin, LOW);
digitalWrite(redLedPin, HIGH); // Red LED is initially ON
// Initialize the serial communication for debugging
Serial.begin(9600);
}
void loop() {
// Read the light sensor value
int lightLevel = digitalRead(lightSensorPin); // Assumes HIGH when above 300 LUX
// Check if the light level is below 300 LUX (LM393 output is LOW)
if (lightLevel == HIGH) {
if (isLightOn) {
// Light is off now
isLightOn = false;
digitalWrite(greenLedPin, LOW);
digitalWrite(redLedPin, HIGH);
lcd.setCursor(0, 0);
lcd.print("Battery Life: ");
}
} else {
if (!isLightOn) {
// Light is on now
isLightOn = true;
lightOnStartTime = millis();
digitalWrite(greenLedPin, HIGH);
digitalWrite(redLedPin, LOW);
lcd.setCursor(0, 0);
lcd.print("Light On: ");
}
// Calculate the duration the light has been on
unsigned long lightOnDuration = millis() - lightOnStartTime;
// Convert and update the duration on the LCD in HH:MM:SS format
lcd.setCursor(5, 1);
printDurationOnLCD(lightOnDuration);
}
}
void printDurationOnLCD(unsigned long duration) {
unsigned long seconds = duration / 1000;
unsigned long minutes = seconds / 60;
unsigned long hours = minutes / 60;
// Calculate remaining minutes and seconds after hours
seconds %= 60;
minutes %= 60;
// Print the duration on the LCD in HH:MM:SS format with both digits for seconds
if (hours < 10) {
lcd.print("0"); // Add leading zero for single-digit minutes
}
lcd.print(hours);
lcd.print("h"); // Add 'h' for hours
lcd.print(":");
if (minutes < 10) {
lcd.print("0"); // Add leading zero for single-digit minutes
}
lcd.print(minutes);
lcd.print("m"); // Add 'm' for minutes
lcd.print(":");
if (seconds < 10) {
lcd.print("0"); // Add leading zero for single-digit seconds
}
lcd.print(seconds);
lcd.print("s"); // Add 's' for seconds
}