Arduino Distance Meter with HC-SR04 and 16x2 I2C LCD (Wiring + Code)
Build an Arduino distance meter with the HC-SR04 ultrasonic sensor and a 16x2 I2C LCD. Wiring table, full code, calibration and fixes.
In this project you will build a small device that measures distance without touching anything and shows it live on an LCD screen. Point it at a wall, a box or your hand and it shows the distance in centimetres. It is the same idea used in car parking sensors, water tank level meters and robots that avoid obstacles.
You will use two of the most popular beginner modules: the HC-SR04 ultrasonic sensor and a 16x2 LCD with an I2C backpack. The I2C backpack means the LCD needs only 4 wires instead of 12. If you finished the Blink project, you are ready for this.
How the HC-SR04 works (simple version)
The sensor has two "eyes". One is a speaker that sends a short burst of ultrasound (40 kHz, too high for humans to hear). The other is a microphone that listens for the echo.
- The Arduino sends a 10 microsecond pulse to the Trig pin.
- The sensor sends out the sound burst.
- The Echo pin goes HIGH and stays HIGH until the echo comes back.
- The Arduino measures how long Echo was HIGH, in microseconds.
Sound travels at about 0.0343 cm per microsecond (343 m/s at 20 °C). The sound goes there and back, so:
distance (cm) = echo time (µs) × 0.0343 ÷ 2
Example: echo time 1166 µs → 1166 × 0.0343 ÷ 2 ≈ 20 cm.
The HC-SR04 works from about 2 cm to 400 cm. Closer than 2 cm or farther than 4 m, readings become unreliable.
Parts list
| Item | Qty | Notes |
|---|---|---|
| Arduino Uno + USB cable | 1 | Original or clone |
| HC-SR04 ultrasonic sensor | 1 | 5 V module, 4 pins |
| 16x2 LCD with I2C backpack (PCF8574) | 1 | Blue or green; 4 pins: GND, VCC, SDA, SCL |
| Breadboard (half size) | 1 | Optional, makes power sharing easy |
| Jumper wires (male-to-female and male-to-male) | 8 | Female ends fit module pins |
All parts are in the ElectroDai parts list for Project 01.
Wiring table
| Arduino Uno pin | Component | Component pin |
|---|---|---|
| 5V | HC-SR04 | VCC |
| GND | HC-SR04 | GND |
| D9 | HC-SR04 | Trig |
| D10 | HC-SR04 | Echo |
| 5V | I2C LCD | VCC |
| GND | I2C LCD | GND |
| A4 (SDA) | I2C LCD | SDA |
| A5 (SCL) | I2C LCD | SCL |
The Uno has only one 5V pin, so take 5V and GND to the breadboard's power rails and connect both modules there. On an Uno R3, the two pins next to AREF (labelled SDA and SCL) are the same as A4 and A5 — you can use either.
Step 1: Install the LCD library
- Open Arduino IDE → Tools → Manage Libraries.
- Search LiquidCrystal I2C.
- Install the one by Frank de Brabander.
The Wire library for I2C is built into the IDE. You do not need a library for the HC-SR04.
Step 2: Wire it
Unplug the USB cable first. Follow the wiring table. Double-check that VCC and GND are not swapped on either module — that is the fastest way to kill a module.
Step 3: Upload the code
/*
ElectroDai Project 01 - Ultrasonic Distance Meter
Arduino Uno + HC-SR04 + 16x2 I2C LCD
Library: "LiquidCrystal I2C" by Frank de Brabander (Library Manager)
Wiring:
HC-SR04: VCC->5V, GND->GND, Trig->D9, Echo->D10
I2C LCD: VCC->5V, GND->GND, SDA->A4, SCL->A5
*/
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// ----- Pins -----
const uint8_t TRIG_PIN = 9; // HC-SR04 Trig
const uint8_t ECHO_PIN = 10; // HC-SR04 Echo
// ----- LCD -----
// Most backpacks (PCF8574T chip) use address 0x27.
// Backpacks with the PCF8574AT chip use 0x3F.
// If the backlight is on but no text appears, change 0x27 to 0x3F.
LiquidCrystal_I2C lcd(0x27, 16, 2);
// ----- Calibration -----
const float AIR_TEMP_C = 25.0; // room temperature in degrees C (sound is faster in warm air)
const float CAL_OFFSET_CM = 0.0; // fine correction after checking with a ruler
// ----- Limits -----
const unsigned long ECHO_TIMEOUT_US = 30000UL; // stop waiting after 30 ms (about 5 m)
const float MIN_CM = 2.0; // HC-SR04 useful range
const float MAX_CM = 400.0;
float soundSpeedCmPerUs; // calculated in setup()
// Send one ping and return distance in cm, or -1 if no echo came back
float readOnceCm() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH); // 10 us pulse starts a measurement
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
unsigned long echoUs = pulseIn(ECHO_PIN, HIGH, ECHO_TIMEOUT_US);
if (echoUs == 0) {
return -1.0; // timeout: nothing in range
}
// divide by 2 because the sound goes to the object and back
return (echoUs * soundSpeedCmPerUs) / 2.0 + CAL_OFFSET_CM;
}
// Take several readings and average only the valid ones
float readAverageCm(uint8_t samples) {
float total = 0.0;
uint8_t good = 0;
for (uint8_t i = 0; i < samples; i++) {
float d = readOnceCm();
if (d >= MIN_CM && d <= MAX_CM) {
total += d;
good++;
}
delay(60); // HC-SR04 needs about 60 ms between pings
}
if (good == 0) {
return -1.0;
}
return total / good;
}
// Print text on LCD line 2, padded with spaces so old characters are erased
void printLine2(const char *text) {
char buf[17]; // 16 characters + end-of-string
snprintf(buf, sizeof(buf), "%-16s", text);
lcd.setCursor(0, 1);
lcd.print(buf);
}
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
digitalWrite(TRIG_PIN, LOW);
Serial.begin(9600);
// Speed of sound: 331.3 + 0.606 x temperature (m/s), converted to cm per microsecond
soundSpeedCmPerUs = (331.3 + 0.606 * AIR_TEMP_C) / 10000.0;
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("ElectroDai");
lcd.setCursor(0, 1);
lcd.print("Distance Meter");
delay(1500);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Distance:");
}
void loop() {
float distance = readAverageCm(3);
if (distance < 0) {
printLine2("Out of range");
Serial.println("Out of range");
} else {
char number[8];
char line[17];
dtostrf(distance, 5, 1, number); // e.g. " 25.4" (1 decimal place)
snprintf(line, sizeof(line), "%s cm", number);
printLine2(line);
Serial.print(distance, 1);
Serial.println(" cm");
}
delay(100);
}
Select Arduino Uno and the right port, then click Upload.
Step 4: Adjust the LCD contrast
On the back of the I2C backpack there is a small blue potentiometer. If the screen is lit but shows nothing (or only white boxes), turn it slowly with a small screwdriver until the text appears. This one fix solves most "blank LCD" problems.
Step 5: Test and calibrate
- Put a flat object (a book or box) in front of the sensor.
- Measure the real distance from the front of the sensor's metal cylinders to the object with a ruler. Try 10 cm, 30 cm and 100 cm.
- Compare with the LCD.
- If the room is hot or cold, set
AIR_TEMP_Cto the real temperature. For example, at 15 °C sound is about 2% slower than at 25 °C. - If every reading is off by the same amount (for example always 1 cm too high), set
CAL_OFFSET_CM = -1.0. Upload again.
A good HC-SR04 is usually within about ±1 cm on a flat, hard surface up to 1–2 m.
Troubleshooting
| Problem | Likely cause | Fix |
|---|---|---|
| LCD backlight on, no text | Contrast too low/high | Turn the blue potentiometer on the backpack |
| Still no text after contrast | Wrong I2C address | Change 0x27 to 0x3F, or run an I2C scanner sketch to find the address |
| LCD shows nothing, no backlight | VCC/GND not connected | Check 5V and GND to the LCD |
Compile error about LiquidCrystal_I2C |
Library missing or wrong one | Install "LiquidCrystal I2C" by Frank de Brabander |
| Always "Out of range" | Trig/Echo swapped or loose | Trig→D9, Echo→D10; reseat jumpers |
| Readings jump randomly | Soft or angled target, loose wires | Use a flat hard target, face it straight on |
| Reads 0–3 cm all the time | Object too close, or sensor touching something | Keep at least 2 cm clear in front |
FAQ
Can I use the HC-SR04 with an ESP32? Yes, but the ESP32 runs at 3.3 V. Power the HC-SR04 from 5 V and put a voltage divider (for example 1 kΩ and 2 kΩ) on the Echo line so the ESP32 pin only sees about 3.3 V. Or use the 3.3 V-friendly HC-SR04P version.
Why does it not detect soft things like cloth or foam well? Soft and angled surfaces absorb or deflect the sound, so less echo returns. Hard flat surfaces give the best results.
Can I show the distance in inches? Yes. Divide the cm value by 2.54 and change the "cm" text to "in".
Watch the video
📺 [VIDEO PLACEHOLDER — embed ElectroDai long video #1: "Arduino Distance Meter with HC-SR04 + I2C LCD"]
Want more? The full build sheet adds a buzzer alarm and turns this into a car parking sensor.