Without LED
#include <Wire.h> // Required for I2C communication
#include <LiquidCrystal_I2C.h> // Include the LCD library
// Define the pins for the HC-SR04 sensor
const int trigPin = 9; // You can change this to the digital pin you used
const int echoPin = 10; // You can change this to the digital pin you used
// Set the LCD's I2C address, number of columns, and number of rows
// You NEED to change the address (0x27) if yours is different!
// Common addresses are 0x27 and 0x3F
// Change 16 and 2 to match your LCD (e.g., 20, 4 for a 20x4 LCD)
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Variables for the distance measurement
long duration; // Time it takes for the ultrasonic pulse to return
int distanceCm; // Calculated distance in centimeters
int distanceInch; // Calculated distance in inches
void setup() {
// --- HC-SR04 Setup ---
pinMode(trigPin, OUTPUT); // Set the trigger pin as an output
pinMode(echoPin, INPUT); // Set the echo pin as an input
// --- LCD Setup ---
[Link](); // Initialize the LCD
[Link](); // Turn on the backlight
// Optional: Start Serial Monitor for debugging
[Link](9600);
[Link]("HC-SR04 Test with I2C LCD");
// Initial LCD display
[Link](0, 0);
[Link]("Distance:"); // Label for distance on the first line
}
void loop() {
// --- HC-SR04 Measurement ---
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Send a 10 microsecond pulse to trigger the sensor
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the pulse on the echoPin
// pulseIn() returns the length of the pulse in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
// The speed of sound is about 343 m/s, or 0.0343 cm/microsecond.
// The pulse travels to the object and back, so we divide the duration
by 2.
// Distance (cm) = (duration / 2) * speed of sound (cm/us)
distanceCm = duration * 0.0343 / 2;
// Calculate distance in inches
distanceInch = duration * 0.0135 / 2; // Speed of sound is about 0.0135
inch/microsecond
// --- Display on LCD ---
// Clear the previous distance value on the LCD
// We print spaces to overwrite the old numbers
[Link](9, 0); // Go to the position where the value starts
(adjust if your label is shorter/longer)
[Link](" "); // Print enough spaces to clear the previous
number and unit
// Set the cursor back to the position for the value
[Link](9, 0);
[Link](distanceCm); // Print the distance
[Link](" cm"); // Print the unit
// Optional: Display inches on the second line
[Link](0, 1);
[Link]("Inches: ");
[Link](distanceInch);
[Link](" in "); // Print enough spaces to clear previous value if
needed
// Optional: Print to Serial Monitor for debugging
[Link]("Distance: ");
[Link](distanceCm);
[Link](" cm");
// Wait before taking the next measurement
delay(2000); // Measure every 2 seconds
}