#include <LiquidCrystal.h>
// initialize the LCD library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const int TRIGGER_PIN = 7; // connect the trigger pin of the sensor to digital pin 7
const int ECHO_PIN = 6; // connect the echo pin of the sensor to digital pin 6
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// initialize the trigger and echo pins of the sensor
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
void loop() {
// send a 10 microsecond pulse to the sensor's trigger pin
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
// measure the time it takes for the echo signal to arrive
long duration = pulseIn(ECHO_PIN, HIGH);
// calculate the distance in centimeters based on the speed of sound
int distance_cm = duration / 58;
// display the distance on the LCD
lcd.setCursor(0, 0);
lcd.print("Distance: ");
lcd.print(distance_cm);
lcd.print("cm");
// print the distance to the Serial monitor
Serial.print("Distance: ");
Serial.print(distance_cm);
Serial.println("cm");
delay(1000); // wait 1 second before taking another measurement
}