#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Pin assignments
const int TRIG_PIN = 2;
const int ECHO_PIN = 3;
// Initialize LCD: Address 0x27, 16 columns, 2 rows
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
// Pin modes for sensor
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
// Initialize communication interfaces
Serial.begin(9600);
lcd.init();
lcd.backlight();
// Print initial splash screen
lcd.setCursor(0, 0);
lcd.print("Distance Monitor");
lcd.setCursor(0, 1);
lcd.print("Initializing...");
delay(1500);
lcd.clear();
}
void loop() {
// Clear trigger pin
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
// Send a 10-microsecond HIGH pulse to trigger the sensor
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Read the bounce-back travel time in microseconds
long duration = pulseIn(ECHO_PIN, HIGH);
// Calculate distance in centimeters
// Speed of sound is ~343 m/s or 0.0343 cm/us. Divide by 2 for round-trip.
int distance = duration * 0.0343 / 2;
// Serial Monitor output for debugging
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Update the visual display panel
lcd.setCursor(0, 0);
lcd.print("Target Status: ");
lcd.setCursor(0, 1);
if (distance > 400 || distance <= 0) {
lcd.print("Out of Range ");
} else {
lcd.print("Dist: ");
lcd.print(distance);
lcd.print(" cm "); // Extra spaces clear old characters
}
// Wait 200ms before taking the next reading to prevent echoing overlap
delay(200);
}