UniRemoteLab عربي Deutsch Open the lab

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
HC-SR04 distanceHC-SR04 distance

Wiring on the lab board

PartPin
TRIGGPIO4
ECHOGPIO16
OLED SDA / SCLGPIO22 / 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

  1. A 10 µs HIGH pulse on TRIG makes the sensor fire eight sound pulses and raise ECHO until the echo returns.
  2. 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.
  3. 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.

No ESP32 at hand?

Run this code now on a real board in our remote lab: write, upload, and watch the result live on camera.

Open the lab

More tutorials