#include <Wire.h> // For I2C communication
#include <LiquidCrystal_I2C.h> // Library for I2C LCD
// Set the LCD address to 0x27 (adjust if necessary), with 16 columns and 2 rows
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Define pins for HC-SR04
const int trigPin = 9;
const int echoPin = 10;
void setup() {
lcd.begin(16, 2); // Initialize the LCD with 16 columns and 2 rows
lcd.backlight(); // Turn on the LCD backlight
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// Generate a 10us pulse to trigger the sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the echo pulse
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance in cm
float distance = duration * 0.034 / 2;
// Print the distance on the LCD
lcd.clear();
lcd.setCursor(0, 0); // Set cursor to the first row, first column
lcd.print("Distance: ");
lcd.print(distance);
lcd.print(" cm");
delay(500); // Delay to avoid rapid updates
}