Measure Distance with an HC-SR04 and ESP32 on an OLED
The HC-SR04 sends an inaudible sound pulse and times its echo off an object in front of it. The ESP32 turns that into centimetres and shows it as a number and a bar on the OLED.
▶ Run it on a real boardFree as a guest for a few minutes, or with your university account


Wiring on the lab board
| Part | Pin |
|---|---|
| TRIG | GPIO4 |
| ECHO | GPIO16 |
| OLED SDA / SCL | GPIO22 / GPIO23 |
Full code
// Experiment 4: distance sensor HC-SR04 shown on the OLED
// Relays: K1 (ECHO), K2 (TRIG), K5 and K6 (I2C for the display)
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
const int TRIG = 4;
const int ECHO = 16;
Adafruit_SSD1306 display(128, 64, &Wire, -1);
float readCm() {
digitalWrite(TRIG, LOW); delayMicroseconds(2);
digitalWrite(TRIG, HIGH); delayMicroseconds(10);
digitalWrite(TRIG, LOW);
long us = pulseIn(ECHO, HIGH, 30000); // 30 ms timeout
return us * 0.0343 / 2;
}
void setup() {
Serial.begin(115200);
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
Wire.begin(22, 23);
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) Serial.println("OLED not found");
display.setRotation(2); // the OLED is mounted upside down on this board: rotate 180°
display.setTextColor(SSD1306_WHITE);
}
void loop() {
float cm = readCm();
Serial.println(cm);
display.clearDisplay();
display.setTextSize(1); display.setCursor(0, 0); display.println("Distance");
display.setTextSize(3); display.setCursor(0, 24);
if (cm <= 0) display.println("---"); else { display.print(cm, 0); display.setTextSize(2); display.println(" cm"); }
int bar = constrain((int)(cm * 128 / 100), 0, 128); // bar up to 100 cm
display.fillRect(0, 58, bar, 6, SSD1306_WHITE);
display.display();
delay(300);
}
The libraries are already installed in the lab.
How it works
- A 10 µs HIGH pulse on TRIG makes the sensor fire eight sound pulses and raise ECHO until the echo returns.
- pulseIn(ECHO, HIGH, 30000) measures how long ECHO stayed HIGH in microseconds. Sound travels 0.0343 cm per µs, and the path is there and back, so we divide by 2.
- The 30000 µs timeout keeps the code from hanging when no echo returns; pulseIn() then returns 0 and the screen shows ---.
Common mistakes and fixes
- The reading is always 0
- The TRIG or ECHO relay is open, or nothing is within about 4 m.
- Readings jump around
- Slanted or soft surfaces scatter the sound. Average several readings.
- The code freezes
- Use pulseIn() with a timeout, as in the code.
SG90 servo
DS3502 digital pot
AC dimmer