#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Define the ultrasonic sensor pins
#define trigPin 9
#define echoPin 10
// Create an LCD object with the I2C address 0x27 and 16 columns, 2 rows
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Variable to store the duration of the pulse and distance
long duration;
int distance;
void setup() {
// Initialize the serial monitor
Serial.begin(9600);
// Initialize the ultrasonic sensor pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Initialize the LCD
lcd.begin(16, 2);
lcd.setCursor(0, 0);
lcd.print("Distance Sensor");
delay(2000); // Display the message for 2 seconds
// Clear the LCD screen
lcd.clear();
}
void loop() {
// Send a 10us pulse to trigger the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the pulse received on the echo pin
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
distance = duration * 0.0344 / 2; // Speed of sound is 0.0344 cm/µs, divide by 2 for round-trip
// Display the distance on the LCD
lcd.setCursor(0, 0); // Set the cursor to the first row
lcd.print("Distance: ");
lcd.print(distance); // Print the distance value
lcd.print(" cm");
// Print the distance to the Serial Monitor (optional)
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Wait for a short time before the next reading
delay(500); // Update every 500 milliseconds
}