/*
* Created by ArduinoGetStarted.com
*
* This example code is in the public domain
*
* Tutorial page: [Arduino - Ultrasonic Sensor - LCD](https://arduinogetstarted.com/tutorials/arduino-ultrasonic-sensor-lcd)
*/
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C address 0x27 (from DIYables LCD), 16 columns and 2 rows
int trigPin = 9; // TRIG pin
int echoPin = 10; // ECHO pin
float duration_us, distance_cm;
void setup() {
lcd.init(); // Initialize the LCD
lcd.backlight(); // Turn on the backlight
pinMode(trigPin, OUTPUT); // Configure the trigger pin as output
pinMode(echoPin, INPUT); // Configure the echo pin as input
}
void loop() {
// Generate a 10-microsecond pulse to the TRIG pin
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the pulse from the ECHO pin
duration_us = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
distance_cm = 0.017 * duration_us;
// Display the distance on the LCD
lcd.clear();
lcd.setCursor(0, 0); // Start printing at the first row
lcd.print("Distance: ");
lcd.print(distance_cm);
delay(500); // Wait for a moment before measuring again
}