#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Initialize the LCD with the I2C address 0x27 for a 16x2 LCD
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Define the pins for the ultrasonic sensor
const int trigPin = 7;
const int echoPin = 6;
// Define variables to store the duration and distance
long duration;
int distance;
void setup() {
// Initialize the LCD and turn on the backlight
lcd.begin(16, 2);
lcd.backlight();
// Set up the ultrasonic sensor pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Print initial message on LCD
lcd.setCursor(0, 0);
lcd.print("Distance: ");
}
void loop() {
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Send a 10 microsecond pulse to the trigPin
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin and calculate the duration
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
distance = duration * 0.034 / 2;
// Display the distance on the LCD
lcd.setCursor(10, 0); // Move the cursor to the right part of the screen
lcd.print(" "); // Clear previous value
lcd.setCursor(10, 0); // Set cursor again
lcd.print(distance); // Display the distance
lcd.print(" cm");
// Wait for a short period before taking another measurement
delay(500);
}