#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // Set the LCD address to 0x27 for a 16 chars and 2 line display
const int trigPin = 9; // Trigger pin of the ultrasonic sensor
const int echoPin = 10; // Echo pin of the ultrasonic sensor
long duration;
int distance;
void setup() {
lcd.init(); // Initialize the LCD
lcd.backlight(); // Turn on backlight
pinMode(trigPin, OUTPUT); // Set trigger pin as OUTPUT
pinMode(echoPin, INPUT); // Set echo pin as INPUT
lcd.print("Distance:"); // Print "Distance:" on LCD
}
void loop() {
// Clear the display
lcd.setCursor(0, 1);
lcd.print(" ");
// Trigger the ultrasonic sensor by sending a 10 microsecond HIGH pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the echo pulse
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
distance= duration*0.034/2;
// Print the distance on LCD
lcd.setCursor(0, 1);
lcd.print(distance);
lcd.print(" cm");
// Delay before next measurement
delay(500);
}