Submit

10 / 20

Distance meter

Time an ultrasonic echo and show centimeters on an OLED.

Run this experiment →
ESP32 teaching illustration with module, GPIO headers and lesson components

Why it’s here

Move the obstacle and compare echo time, the numeric display and the bar.

How it works

Time an ultrasonic echo and show centimeters on an OLED. The pulse travels to the obstacle and back. Distance uses only the one-way travel. This guided model targets the original ESP32 and Arduino-ESP32 3.x; radio, acoustics, loads and mechanics are simplified.

Try it

  1. Open this experiment
  2. Move the obstacle and compare echo time, the numeric display and the bar.

Connections

  • GPIO 5 / 19 — TRIG / 3.3V-compatible ECHO
  • GPIO 21 / 22 — OLED SDA / SCL · 3V3/GND

Example sketch

#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
Adafruit_SSD1306 display(128, 64, &Wire, -1);
// Use a 3.3V-compatible HC-SR04P. A 5V ECHO needs a divider.

void setup() {
  Serial.begin(115200);
  pinMode(5, OUTPUT); pinMode(19, INPUT);
  Wire.begin(21, 22);
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
}

void loop() {
  digitalWrite(5, LOW); delayMicroseconds(2);
  digitalWrite(5, HIGH); delayMicroseconds(10);
  digitalWrite(5, LOW);
  unsigned long echo = pulseIn(19, HIGH, 30000);
  float cm = echo ? echo / 58.0f : -1;
  display.clearDisplay(); display.setTextColor(SSD1306_WHITE);
  display.setTextSize(2); display.setCursor(0, 0);
  if (cm < 0) display.print("No echo"); else { display.print(cm, 1); display.print(" cm"); }
  display.display(); Serial.println(cm);
  delay(100);
}

Check your understanding

Why divide the round-trip time by two?

Show the answer

The pulse travels to the obstacle and back. Distance uses only the one-way travel.

Sources

Arduino-ESP32 ↗ · GPIO reference ↗

MAKE A THOUGHTFUL CHOICE

Your shortlist, side by side.

Pricing models are indicative. Check each official website for current plans and limits.