#include <LiquidCrystal.h>
// Initialize the LCD with the interface pins
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
// Define pins for the Ultrasonic Sensor
const int trigPin = 9;
const int echoPin = 10;
void setup() {
// Set up the LCD's number of columns and rows
lcd.begin(16, 2);
lcd.print("Distance:");
// Set up the ultrasonic sensor pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the trigPin HIGH for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin, returns the sound wave travel time in microseconds
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
int distance = duration * 0.034 / 2;
// Clear the previous distance from the LCD
lcd.setCursor(0, 1);
lcd.print(" ");
// Set the cursor to the second row, first column
lcd.setCursor(0, 1);
// Print the distance on the LCD
lcd.print(distance);
lcd.print(" cm");
// Wait before the next reading
delay(500);
}