Complete Guide: ESP32 Ultrasonic Distance Meter with LCD Display - Wokwi Simulator Tutorial

ESP32 Ultrasonic Distance Meter with LCD (I2C) – Wokwi Tutorial | MakeMindz
📡 IoT Tutorial

ESP32 Ultrasonic Distance Meter with 16×2 LCD (I2C)

Build a real-time distance measurement system using the ESP32, HC-SR04 ultrasonic sensor, and a 16×2 I2C LCD — and simulate it entirely online with Wokwi.

ESP32 DevKit V1 📏 HC-SR04 Sensor 🖥 16×2 I2C LCD 🧪 Wokwi Simulation

🚀 No hardware needed — simulate this project directly in your browser

▶ Open in Wokwi Simulator
📐

Project Overview

2–400 Detection Range (cm)
40kHz Ultrasonic Frequency
2s Refresh Interval
I2C LCD Protocol

This system sends ultrasonic pulses, measures the echo return time, and calculates the distance to any object in front of the sensor. The result displays live on a 16×2 LCD screen every 2 seconds.

Distance = (Duration × 0.034) ÷ 2
Speed of sound ≈ 343 m/s  |  Duration measured by pulseIn() in microseconds
🔧

Components Required

📟
ESP32 DevKit V1
Main microcontroller / processor
📡
HC-SR04 Ultrasonic Sensor
2 cm – 400 cm detection range
🖥
16×2 LCD with I2C Module
I2C address: 0x27 (typical)
🔌
Jumper Wires
Male-to-male, assorted colors
5V USB Power Supply
Via ESP32 USB or external 5V
🔗

Circuit Connections

Two separate modules connect to the ESP32. Follow each table carefully.

HC-SR04 Ultrasonic Sensor → ESP32

HC-SR04 Pin ESP32 Pin Wire Color Function
VCC 5V / 3.3V Red Power supply
GND GND Black Ground
TRIG GPIO 32 Green Trigger pulse (OUTPUT)
ECHO GPIO 33 Yellow Echo return (INPUT)

16×2 LCD (I2C) → ESP32

LCD (I2C) Pin ESP32 Pin Wire Color Function
VCC 5V Red Power supply
GND GND Black Ground
SDA GPIO 21 Green I2C Data line
SCL GPIO 22 Blue I2C Clock line
📋

Step-by-Step Build Guide

1
Open Wokwi Simulator
Go to wokwi.com and create a new ESP32 project. Select ESP32 DevKit V1 as your board template.
💡 You can use the Wokwi link provided at the top of this page to jump directly into a pre-configured simulation.
2
Add the diagram.json
Click the diagram.json tab in Wokwi and replace its contents entirely with the JSON provided in Step 5 below. This defines all parts and their wiring connections.
💡 This JSON includes the ESP32, HC-SR04, and 16×2 I2C LCD with all connections pre-wired — no manual dragging required.
3
Install the Required Library
In Wokwi, open the Library Manager and add LiquidCrystal_I2C by Frank de Brabander. In the Arduino IDE, use Sketch → Include Library → Manage Libraries and search for it.
💡 Wokwi handles this automatically if the library is listed in the sketch — just add #include <LiquidCrystal_I2C.h> at the top.
4
Paste the Arduino Code
Click the sketch.ino tab in Wokwi and replace all content with the complete code from Step 6 below. Check that GPIO pins (32, 33, 21, 22) and the I2C address (0x27) match your setup.
⚠️ If your LCD shows blank rows, the I2C address may differ. Try 0x3F instead of 0x27.
5
Run the Simulation
Click the green ▶ Play button. The LCD backlight will turn on, "Distance :" appears on row 1, and the measured distance (in cm) updates on row 2 every 2 seconds. Move the virtual sensor slider in Wokwi to change the simulated distance.
6
Monitor Serial Output
Open the Serial Monitor at the bottom of Wokwi (baud rate 115200) to see raw duration and distance values logged in real time — useful for debugging sensor readings.
🗺

Wokwi diagram.json

Copy this entire JSON and paste it into the diagram.json tab inside Wokwi. It defines all components, positions, and wiring connections.

📄 diagram.json
{
  "version": 1,
  "author": "MakeMindz",
  "editor": "wokwi",
  "parts": [
    { "type": "wokwi-esp32-devkit-v1", "id": "esp",
      "top": 0, "left": 0, "attrs": {} },

    { "type": "wokwi-hc-sr04", "id": "ultrasonic1",
      "top": 12.87, "left": -228.6, "attrs": {} },

    { "type": "wokwi-gnd", "id": "gnd1",
      "top": 117.19, "left": -127.89, "attrs": {} },

    { "type": "wokwi-gnd", "id": "gnd2",
      "top": 128.95, "left": 197.42, "attrs": {} },

    { "type": "wokwi-vcc", "id": "vcc1",
      "top": 115.61, "left": -226.85, "attrs": {} },

    { "type": "wokwi-vcc", "id": "vcc2",
      "top": 11.36, "left": 186.26, "attrs": {} },

    {
      "type": "wokwi-lcd1602",
      "id": "lcd1",
      "top": 29.34,
      "left": 232.42,
      "attrs": { "pins": "i2c" }
    }
  ],
  "connections": [
    [ "esp:TX0",          "$serialMonitor:RX", "",       [] ],
    [ "esp:RX0",          "$serialMonitor:TX", "",       [] ],
    [ "vcc1:VCC",         "ultrasonic1:VCC",   "red",    ["v8.82","h59.56"] ],
    [ "ultrasonic1:GND",  "gnd1:GND",          "black",  ["v0"] ],
    [ "lcd1:GND",         "gnd2:GND",          "black",  ["h-31.96","v1.78"] ],
    [ "vcc2:VCC",         "lcd1:VCC",          "red",    ["v0"] ],
    [ "lcd1:SDA",         "esp:D21",           "green",  ["h-104.08","v-18.01"] ],
    [ "esp:D22",          "lcd1:SCL",          "blue",   ["h73.37","v52.63"] ],
    [ "ultrasonic1:TRIG", "esp:D32",           "green",  ["v56.87","h122.87","v-93.28"] ],
    [ "esp:D33",          "ultrasonic1:ECHO",  "yellow", ["h-47.46","v98.21","h-91.71"] ]
  ],
  "dependencies": {}
}
💻

Arduino Code (sketch.ino)

Paste this into the sketch.ino tab in Wokwi, or upload it via the Arduino IDE to your physical ESP32 board.

⚙️ sketch.ino (Arduino / C++)
#include <LiquidCrystal_I2C.h>

// LCD config: 16 columns, 2 rows
int lcdColumns = 16;
int lcdRows    = 2;

// HC-SR04 pin definitions
int trigPin = 32;
int echoPin = 33;

float duration;
int   distance;

// I2C address 0x27 — try 0x3F if LCD stays blank
LiquidCrystal_I2C lcd(0x27, lcdColumns, lcdRows);

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  lcd.init();        // Initialize the LCD
  lcd.backlight();  // Turn on backlight
}

void loop() {

  // --- Trigger the HC-SR04 ---
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);  // 10µs trigger pulse
  digitalWrite(trigPin, LOW);

  // --- Measure echo duration ---
  duration = pulseIn(echoPin, HIGH);

  // --- Calculate distance in centimeters ---
  // distance = (time × speed_of_sound) / 2
  distance = (duration * 0.034) / 2;

  // --- Display on LCD ---
  lcd.setCursor(0, 0);       // Row 0, Col 0
  lcd.print("Distance :");

  lcd.setCursor(1, 3);       // Row 1, Col 3
  lcd.print(distance);       // Print distance value

  delay(2000);               // Wait 2 seconds
  lcd.clear();               // Clear screen
}
📌 Key Settings to Know
  • 0x27 — Default I2C address. Use 0x3F if LCD shows nothing.
  • GPIO 32 — Trigger pin. Change only if you rewire the circuit.
  • GPIO 33 — Echo pin. Change only if you rewire the circuit.
  • 0.034 — Speed of sound in cm/µs (343 m/s converted).
  • delay(2000) — Refresh interval. Decrease to 500 for faster updates.
⚙️

How It Works

📤
Trigger pulse sent
ESP32 sends a 10 µs HIGH pulse to GPIO 32 (TRIG pin), telling the HC-SR04 to fire.
🔊
Ultrasonic burst emitted
The sensor fires 8 ultrasonic pulses at 40 kHz — inaudible to humans, but bounce off nearby objects.
🔁
Echo received
The echo returns and HC-SR04 holds the ECHO pin HIGH for the exact duration the sound traveled.
🧮
Distance calculated
ESP32 reads the echo pulse duration with pulseIn() and applies the formula: Distance = (µs × 0.034) ÷ 2.
🖥
LCD displays the result
The distance in centimeters is printed on the 16×2 LCD via I2C. The display refreshes every 2 seconds.
🚀

Real-World Applications

🚗
Smart Parking Assistance
🤖
Robot Obstacle Avoidance
💧
Water Level Monitoring
🚪
Automatic Door Systems
🏭
Industrial Automation
🏠
Smart Home Projects
🔐
Security & Surveillance
📦
Inventory Level Detection
🎓

What You Will Learn

How ultrasonic sensing works — trigger, echo, and time-of-flight calculation
Configuring ESP32 GPIO pins as INPUT and OUTPUT in Arduino code
Using the I2C communication protocol to control a 16×2 LCD with only 2 data wires
Reading sensor data in real time and converting raw microseconds into human-readable distances
Building and simulating IoT circuits in Wokwi — no physical hardware needed
Structuring an ESP32 Arduino sketch with setup(), loop(), and library imports

🧪 Simulate This Project for Free

No hardware, no soldering, no cost. Open Wokwi, paste the JSON and code from this tutorial, and run your distance meter right in the browser.

▶ Launch Wokwi Simulator
✓ Free to use ✓ Real-time serial monitor ✓ Modify code instantly ✓ No installation required

Comments

try for free