tutorialspinouttools
Sensors · ESP32-C3

HC-SR04 on OLED: Live Distance Meter

Free ESP32 & Arduino tutorial · wiring, code & parts · gokul.builds

Overview & Wiring

Measure distance with the HC-SR04 ultrasonic sensor and show it in big digits on the OLED - a standalone range finder. Wiring: OLED -> VCC=3V3, GND=GND, SDA=GPIO4, SCL=GPIO5 HC-SR04 -> VCC=5V/VIN, Trig=GPIO6, Echo=GPIO7, GND=GND Echo outputs 5V. For a permanent build add a 1k+2k divider on Echo, or use a 3.3V-tolerant module. Fine for quick tests. Libraries: Adafruit SSD1306, Adafruit GFX.

Circuit Diagram

HC-SR04 on OLED: Live Distance Meter wiring diagram for ESP32-C3

Parts You Need

ESP32-C3 SuperMiniBuy →
0.96" SSD1306 OLEDBuy →

Source Code (Arduino / ESP32)

#include <Wire.h>              // I2C for the OLED
#include <Adafruit_GFX.h>     // graphics functions
#include <Adafruit_SSD1306.h> // OLED driver

Adafruit_SSD1306 display(128, 64, &Wire, -1); // 128x64 OLED over I2C

#define TRIG 6                 // Trig pin fires the pulse (GPIO6)
#define ECHO 7                 // Echo pin receives the reflection (GPIO7)

void setup() {
  Serial.begin(115200);                      // Serial for debugging
  Wire.begin(4, 5);                          // OLED I2C on GPIO4/GPIO5
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // start OLED at 0x3C
  pinMode(TRIG, OUTPUT);                      // Trig = output
  pinMode(ECHO, INPUT);                       // Echo = input
}

void loop() {
  // fire a clean 10us pulse to trigger the sensor
  digitalWrite(TRIG, LOW);  delayMicroseconds(2);
  digitalWrite(TRIG, HIGH); delayMicroseconds(10);
  digitalWrite(TRIG, LOW);

  long dur = pulseIn(ECHO, HIGH, 30000);     // round-trip time in us (30ms timeout)
  float cm = dur * 0.0343 / 2;               // us -> cm, halved for one-way

  display.clearDisplay();                    // erase previous frame
  display.setTextColor(SSD1306_WHITE);
  display.setTextSize(1);                    // small label
  display.setCursor(0, 0);
  display.println("Distance");

  if (dur == 0) {                            // no echo came back
    display.setTextSize(2);
    display.setCursor(0, 26);
    display.print("Out of range");
    Serial.println("Out of range");
  } else {
    display.setTextSize(3);                  // big value font
    display.setCursor(0, 22);
    display.printf("%.0f", cm);              // distance, no decimals
    display.setTextSize(2);
    display.print(" cm");
    // bar: nearer = fuller (map 0..50cm across the 128px width)
    int bar = map((int)cm, 0, 50, 128, 0);
    if (bar < 0) bar = 0;
    if (bar > 128) bar = 128;
    display.fillRect(0, 56, bar, 8, SSD1306_WHITE);
    Serial.printf("Distance: %.1f cm\n", cm);
  }
  display.display();                         // push to screen
  delay(150);                                // ~6-7 updates/sec
}
Browse all tutorials ESP32-C3 pinout Calculators