#include <Wire.h>
#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 = 8; // ECHO pin
int ledPin = 13; // LED pin
float duration_us, distance_cm;
void setup() {
lcd.init(); // initialize the LCD
lcd.backlight(); // turn on the backlight
pinMode(trigPin, OUTPUT); // configure trigger pin to output mode
pinMode(echoPin, INPUT); // configure echo pin to input mode
pinMode(ledPin, OUTPUT); // configure LED pin to output mode
}
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
distance_cm = 0.017 * duration_us;
// clear the LCD
lcd.clear();
// print distance measurement
lcd.setCursor(0, 0); // start printing at the first row
lcd.print("Distance: ");
lcd.print(distance_cm);
lcd.print(" cm");
// check if the distance exceeds a certain threshold
if (distance_cm > 10) { // for example, if the distance is greater than 10 cm
digitalWrite(ledPin, HIGH); // turn on the LED
lcd.setCursor(0, 1); // start printing at the second row
lcd.print("Warning: Too far");
} else {
digitalWrite(ledPin, LOW); // turn off the LED
}
delay(500); // wait for a while before taking the next measurement
}