HC-SR04 ultrasonic distance sensor with ESP32
How to connect an HC-SR04 ultrasonic distance sensor to an ESP32: the wiring, a sketch that works, and a simulator to try it in your browser before you build it.

HC-SR04 ultrasonic ranger · 5 V · send a 10 µs pulse on TRIG; ECHO then goes HIGH for 58 µs per cm (out to about 4 m) · ECHO is a 5 V signal: divide it down for a 3.3 V board
Wiring
| HC-SR04 ultrasonic distance sensor pin | ESP32 |
|---|---|
| VCC | + of the 5 V supply |
| TRIG | GPIO5 |
| ECHO | GPIO18 (through a 1 kΩ resistor) |
| GND | GND |
The HC-SR04 runs on 5 V and its ECHO pin answers with 5 V: on an ESP32 (3.3 V pins) put a resistor in the ECHO line, or better a 1 kΩ / 2 kΩ divider, as the wiring shows.
Run it in the labFree, no account needed. The same wiring, with the sketch already on the board.
Code
From the project ESP32 water tank level meter: HC-SR04 and OLED. It also compiles in the Arduino IDE (ESP32 core 3.x) with the libraries it includes.
// Water tank level: an HC-SR04 at the top of the tank (TRIG GPIO5, ECHO GPIO18 through a 1k/2k divider, since ECHO is 5 V)
// measures the gap to the water; the OLED shows the level in %; the red LED (GPIO26) lights below 20 %.
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
Adafruit_SSD1306 display(128, 64, &Wire, -1);
const int TRIG = 5, ECHO = 18, LOW_LED = 26;
const float EMPTY_CM = 100, FULL_CM = 20; // gap to the water when the tank is empty / full
void setup() {
Serial.begin(115200);
pinMode(TRIG, OUTPUT); pinMode(ECHO, INPUT); pinMode(LOW_LED, OUTPUT);
Wire.begin(21, 22);
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) Serial.println("OLED not found");
}
void loop() {
digitalWrite(TRIG, LOW); delayMicroseconds(2);
digitalWrite(TRIG, HIGH); delayMicroseconds(10); digitalWrite(TRIG, LOW);
unsigned long us = pulseIn(ECHO, HIGH, 30000);
float cm = us / 58.0;
int pct = constrain((int)((EMPTY_CM - cm) * 100 / (EMPTY_CM - FULL_CM)), 0, 100);
digitalWrite(LOW_LED, pct < 20 ? HIGH : LOW);
display.clearDisplay();
display.setTextColor(SSD1306_WHITE);
display.setTextSize(1); display.setCursor(0, 0); display.print("Water tank");
display.setTextSize(3); display.setCursor(0, 20); display.print(pct); display.print("%");
display.drawRect(100, 10, 24, 50, SSD1306_WHITE);
display.fillRect(102, 58 - pct * 46 / 100, 20, pct * 46 / 100, SSD1306_WHITE);
display.display();
Serial.print("Gap "); Serial.print(cm, 0); Serial.print(" cm level "); Serial.print(pct); Serial.println(" %");
delay(500);
}
Also used in
For teachers
The project runs in the browser on a laptop or a phone, so every student can build and test it before the class touches a real board. Assign it on the teacher's page and set what counts as done: a prediction, a hidden fault found, or a passing test sheet.