#include <LiquidCrystal.h>
const int trigPin = 9;
const int echoPin = 10;
// Initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup() {
// Set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("Distance: ");
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
long duration;
int distance;
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distance = duration * 0.034 / 2;
// Print the distance on the LCD
lcd.setCursor(0, 1); // Move the cursor to the second line
lcd.print(" "); // Clear the line
lcd.setCursor(0, 1); // Move the cursor back to the start of the second line
lcd.print(distance);
lcd.print(" cm");
delay(500);
}