#include <LiquidCrystal_I2C.h> //LCD I2C Library
#include <HCSR04.h> // Ultrasonic sensor Library
LiquidCrystal_I2C lcd(0x27, 16, 2); // 16x2 display
UltraSonicDistanceSensor distanceSensor(13, 12); // Initialize the sensor using digital pins 13 (Trig) and 12(Echo).
void setup()
{
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Distance: "); // Clear the line
Serial.begin(9600); // Initialize the serial connection for debugging.
}
void loop()
{
int distance;
// Trigger the HC-SR04 to get a distance measurement
distance = distanceSensor.measureDistanceCm();
if(distance != -1)
{
// Display the distance on the LCD
lcd.setCursor(0, 0);
lcd.print("Distance:"); // Clear the line
lcd.setCursor(9, 0); // Set cursor to the first row, 10th column
lcd.print(distance);
lcd.print("cm ");
}
else
{
// Display the distance on the LCD
lcd.clear();
lcd.setCursor(0, 0); // Set cursor to the first row, 10th column
lcd.print("Out of range.");
}
// Print the distance to the Serial Monitor for debugging
Serial.print("Distance: ");
Serial.print(distance);
Serial.println("cm");
delay(500); // Adjust the delay to control how often the distance is updated
}