#include <Wire.h>
#include <LiquidCrystal_I2C.h>
const int trigPin = 9;
const int echoPin = 8;

LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup() {
  Serial.begin(9600);

  lcd.init();
  lcd.backlight();
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  lcd.setCursor(0, 0);
  lcd.print("Distance:");
}

void loop() {
  // Clear the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(0);

  // Set the trigPin on HIGH state for 10 microseconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(0);
  digitalWrite(trigPin, LOW);

  // Read the echoPin, returns the sound wave travel time in microseconds
  long duration = pulseIn(echoPin, HIGH);

  // Calculate the distance
  float distance = duration * 0.034 / 2;

  // Print the distance on the LCD
  lcd.setCursor(0, 1);
  lcd.print("                "); // Clear the previous distance
  lcd.setCursor(0, 1);
  lcd.print(distance);
  lcd.print(" cm");

  // Print the distance on the Serial Monitor (optional)
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  // Wait for a bit before the next loop
  delay(1000);
}
