#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <RTClib.h> // Include the RTC library
// Define the LCD address, width, and height
LiquidCrystal_I2C lcd(0x27, 16, 2); // Adjust 0x27 if your LCD uses a different I2C address
// Define pin numbers for ultrasonic sensor and LED
const int trigPin = 9;
const int echoPin = 10;
const int ledPin = 7;
// Variables for ultrasonic sensor
long duration;
int distance;
String messages[] = {"Good Morning!", "Have a Nice Day!", "Stay Positive!", "Keep Smiling!", "You Got This!"};
int messageIndex = 0;
// Initialize RTC object
RTC_DS3231 rtc;
void setup() {
// Initialize pins for ultrasonic sensor and LED
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
// Initialize the LCD with 16 columns and 2 rows
lcd.begin(16, 2);
lcd.backlight();
// Initialize the RTC
if (!rtc.begin()) {
lcd.setCursor(0, 0);
lcd.print("RTC not found!");
while (1); // Halt if RTC not found
}
// Clear the LCD at the start (display is empty initially)
lcd.clear();
}
void loop() {
// Trigger the ultrasonic sensor to measure distance
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read echo and calculate distance
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
// Check if an object is within the detection range
if (distance < 50) {
// Turn on the LED
digitalWrite(ledPin, HIGH);
// Get current time and date from RTC
DateTime now = rtc.now();
// Display the message on the first line
lcd.setCursor(0, 0);
lcd.print(messages[messageIndex]);
// Cycle through the messages every 3 seconds
messageIndex = (messageIndex + 1) % 5;
// Display the current date and time on the second line
lcd.setCursor(0, 1);
String dateTimeString = String(now.month()) + "/" + String(now.day()) + "/" + String(now.year()) + " " +
String(now.hour()) + ":" + String(now.minute()) + ":" + String(now.second());
lcd.print(dateTimeString); // Print the formatted date and time
delay(3000); // Display each message for 3 seconds
} else {
// Turn off the LED if no object is detected
digitalWrite(ledPin, LOW);
// Keep the LCD empty if no object is detected
lcd.clear();
}
delay(100); // Small delay before the next loop iteration
}