#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // Initialize the LCD with I2C address 0x27 and 16x2 display
int trigPin = 2; // Pin for the trigger of the ultrasonic sensor
int echoPin = 3; // Pin for the echo of the ultrasonic sensor
long duration; // Variable to store the duration of pulse
int distance; // Variable to store the calculated distance
unsigned long currentTime, previousTime; // Time tracking variables
void setup() {
lcd.init(); // Initialize the LCD
lcd.backlight(); // Turn on the LCD backlight
pinMode(trigPin, OUTPUT); // Set trigger pin as output
pinMode(echoPin, INPUT); // Set echo pin as input
previousTime = millis(); // Initialize previousTime with the current time
lcd.setCursor(0, 0); // Set cursor to the first row, first column
lcd.print("Welcome to Dist calc"); // Display welcome message
delay(2000); // Wait for 2 seconds
lcd.clear(); // Clear the display
}
void loop() {
digitalWrite(trigPin, LOW); // Set trigger pin low for 2 microseconds
delayMicroseconds(2);
digitalWrite(trigPin, HIGH); // Send a 10-microsecond pulse to the trigger pin
delayMicroseconds(10);
digitalWrite(trigPin, LOW); // Set trigger pin low again
// Read the echo pin and calculate the duration
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
distance = duration * 0.0343 / 2;
// Get the current time in seconds
currentTime = millis() / 1000;
// Display the distance on the LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Distance: ");
lcd.print(distance);
lcd.print(" cm");
// Display the elapsed time on the LCD
lcd.setCursor(0, 1);
lcd.print("Time: ");
lcd.print(currentTime);
lcd.print(" sec");
delay(500); // Wait for 500 milliseconds before repeating the loop
}