Skip to content

Distance · ESP32 guide

Interfacing HC-SR04 Ultrasonic Distance Sensor with ESP32

The classic 40 kHz ultrasonic range finder: two pins, a 10 µs pulse, and an echo whose width is the distance.

Updated November 16, 2026 Arduino C++None — uses built-in pulseIn()Also forArduino Uno

What is the HC-SR04?

The HC-SR04 ultrasonic sensor measures distance by sending a short burst of 40 kHz sound and timing the echo reflected from an object. The common module is specified for a nominal 2 cm to 400 cm range and uses four connections: VCC, TRIG, ECHO and GND.

To measure distance, a microcontroller holds TRIG HIGH for at least 10 µs, then measures how long ECHO remains HIGH. That pulse is the sound's round-trip travel time, so the one-way distance is calculated as speed of sound × time ÷ 2. Near 20 °C, a useful shortcut is distance in cm ≈ Echo time in µs ÷ 58.

One electrical detail matters: the classic HC-SR04 is powered from 5 V and its ECHO output is typically 5 V. An Arduino Uno can read it directly; an ESP32, ESP8266 or Raspberry Pi needs a suitable voltage divider or level shifter on ECHO. Use the Arduino Uno wiring and code guide or the ESP32 guide with a protected ECHO input to build it safely.

Specifications

Operating voltage
5 V DC (3.3 V variants exist, see below)
Working current
15 mA
Ultrasonic frequency
40 kHz
Range
2 cm to 400 cm
Ranging accuracy
up to 3 mm (best case)
Measuring angle
15°
Trigger input
10 µs TTL pulse
Echo output
TTL pulse, width proportional to distance
Echo logic level
5 V (on the classic module)
Minimum cycle
above 60 ms between measurements
Distance formula
echo µs ÷ 58 = cm
Board size
45 × 20 × 15 mm
Header
4 pins, 2.54 mm pitch

Figures follow the HC-SR04 datasheet (ElecFreaks, as reproduced by SparkFun). Real-world accuracy depends on the target, angle and temperature, and cheap clones vary. The datasheet's 3 mm accuracy is a best case on a flat hard target.

Pinout

PinNameDescription
1VCC5 V supply. Needs a real 5 V rail, not a 3.3 V pin, to reach rated range.
2TrigTrigger input. Hold HIGH for at least 10 µs to start one measurement. A 3.3 V logic HIGH is accepted.
3EchoOutput. Goes HIGH when the burst is sent and LOW when the echo returns. HIGH time = round trip. Swings to 5 V.
4GNDGround. Must be shared with your microcontroller.

Pin order is printed on the board: VCC, Trig, Echo, GND.

Wiring & code

Setting up HC-SR04 with ESP32

Library

None — uses built-in pulseIn() by Arduino core

None required. The sketches use only functions built into the ESP32 Arduino core; the web page example uses WiFi.h and WebServer.h, which come with it.

This guide shows how to connect the HC-SR04 ultrasonic distance sensor to an ESP32, measure distance with the Arduino framework and stream readings to a local web dashboard. The key safety step is reducing the classic module's 5 V ECHO signal before it reaches an ESP32 GPIO.

The example uses TRIG on GPIO4 and ECHO on GPIO18 through a 1 kΩ / 2 kΩ resistor divider. The sensor is powered from the board's 5 V/VIN pin, while the ESP32 and sensor share GND. If your sensor is a 3.3 V-compatible variant, verify its actual ECHO output and supply specification before changing this wiring. See the HC-SR04 overview for the measurement theory and target limitations.

Why the ESP32 is different from an Uno. The HC-SR04 sends 5 V on its Echo pin. ESP32 pins only tolerate 3.3 V. Connecting them directly can damage the pin, sometimes immediately, sometimes weeks later. Two cheap resistors make it safe, and Step 1 shows exactly how.

At a glance

Time
About 25 minutes
Skill level
Beginner (you will build a small resistor circuit)
Extra parts
One 1 kΩ and one 2 kΩ resistor
You will learn
Voltage dividers, adding the ESP32 to the Arduino IDE, reading distance, serving a web page

What you need

Required parts

  • ESP32 DevKit board

    Qty
    1
    Notes
    The common 30 or 38 pin board. Pin labels may differ slightly between brands.
  • USB cable (data, not charge-only)

    Qty
    1
    Notes
    Micro-USB or USB-C depending on your board.
  • HC-SR04 ultrasonic sensor

    Qty
    1
    Notes
    The classic 5 V version. If yours says HC-SR04P or 3.3 V, you can skip the resistors.
  • Resistor 1 kΩ (brown, black, red)

    Qty
    1
    Notes
    Top half of the voltage divider.
  • Resistor 2 kΩ (red, black, red)

    Qty
    1
    Notes
    Bottom half of the voltage divider. Two 1 kΩ in series also work.
  • Breadboard

    Qty
    1
    Notes
    Half-size is plenty.
  • Jumper wires, male to male

    Qty
    5
    Notes
    Red, black and three others.

Step 1. Wire it up, safely

Unplug the USB cable before wiring.

Why the ECHO divider is essential

The classic HC-SR04 is normally powered from 5 V, and its ECHO output rises to approximately 5 V. ESP32 GPIOs are not 5 V tolerant; Espressif documents a GPIO voltage tolerance limit of 3.6 V. Connecting ECHO directly can overstress the input.

Use two resistors as a voltage divider:

  • Connect ECHO → 1 kΩ → junction.
  • Connect the junction → GPIO18.
  • Connect the junction → 2 kΩ → GND.
  • Connect sensor GND and ESP32 GND together.

At a nominal 5 V ECHO level, the divider gives 5 × 2 / (1 + 2) = about 3.33 V at GPIO18. The 3.3 V TRIG signal from GPIO4 is suitable for the classic module's TTL trigger input. Use a level shifter or recalculate the divider if your module's output or board differs.

Connections

HC-SR04 wired to an ESP32 in the SolderHub Simulator: 5V to VCC, GPIO4 to Trig, Echo through the 1 kΩ + 2 kΩ divider to GPIO18, GND to GND

Wiring: HC-SR04 to ESP32

Component pinESP32 pinNote
VCCVIN (5V)Red wire. The sensor needs real 5 V, not 3V3. VIN carries 5 V when the board is powered over USB.
TrigGPIO4Blue wire. A 3.3 V signal from the ESP32 is enough to trigger the sensor, so no divider here.
EchoGPIO18 via dividerGreen wire to the divider. Echo to the 1 kΩ resistor, the other end of the 1 kΩ to GPIO18, and from that same point a 2 kΩ resistor to GND.
GNDGNDBlack wire. Common ground. The divider only works if the grounds are joined.
  1. 1Push the HC-SR04 into the breadboard so each pin has its own row.
  2. 2Red wire: ESP32 VIN pin to the VCC row. Black wire: ESP32 GND to the GND row.
  3. 3Blue wire: ESP32 GPIO4 to the Trig row.
  4. 4Place the 1 kΩ resistor with one leg in the Echo row and the other leg in a free row. Call that free row the junction.
  5. 5Green wire: from the junction row to ESP32 GPIO18.
  6. 6Place the 2 kΩ resistor with one leg in the junction row and the other leg in the GND row (or on the breadboard's ground rail, joined to ESP32 GND).

Final check. Echo must never touch GPIO18 without the 1 kΩ in between. Check that the green wire to GPIO18 starts at the junction, not at the Echo row.

Why GPIO4 and GPIO18?

Not every ESP32 pin is equally friendly. These two behave well at boot and are easy to reach on most boards.

Pin choices

  • GPIO4, GPIO18, GPIO19, GPIO23

    Use them for this?
    Yes
    Reason
    Normal general-purpose pins.
  • GPIO0, 2, 5, 12, 15

    Use them for this?
    Avoid if you can
    Reason
    Strapping pins. Their state at power-up affects booting.
  • GPIO6 to GPIO11

    Use them for this?
    Never
    Reason
    Connected to the board's flash memory.
  • GPIO34 to GPIO39

    Use them for this?
    Echo only
    Reason
    Input-only pins. They work as Echo but cannot drive Trig.

Step 2. Set up the Arduino IDE for ESP32

The IDE does not know the ESP32 until you add it. You do this once.

  1. 1Install the Arduino IDE (version 2) from arduino.cc.
  2. 2Open File > Preferences (Arduino IDE > Settings on Mac). In Additional boards manager URLs, paste https://espressif.github.io/arduino-esp32/package_esp32_index.json and click OK.
  3. 3Open the Boards Manager (the board icon on the left), search for esp32, and install esp32 by Espressif Systems. It is a large download, so give it a few minutes.
  4. 4Plug the ESP32 into your computer.
  5. 5Click Tools > Board > esp32 and choose ESP32 Dev Module.
  6. 6Click Tools > Port and choose the port that appeared (COM3, /dev/ttyUSB0 or similar). If no port appears, try another cable first, then install the CP210x or CH340 driver that matches the chip on your board.

Step 3. Upload your first sketch

sketch.ino
// HC-SR04 distance meter - ESP32
const int TRIG_PIN = 4;    // ESP32 GPIO4  -> sensor Trig
const int ECHO_PIN = 18;   // ESP32 GPIO18 <- sensor Echo (through the 1k + 2k divider!)

void setup() {
  Serial.begin(115200);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  digitalWrite(TRIG_PIN, LOW);
}

void loop() {
  // 1. 10 microsecond pulse on Trig
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  // 2. Time the Echo pulse (give up after 30 ms)
  unsigned long echoTime = pulseIn(ECHO_PIN, HIGH, 30000UL);

  // 3. Convert to distance
  if (echoTime == 0) {
    Serial.println("No echo - nothing in range?");
  } else {
    float distanceCm = echoTime / 58.0;
    Serial.printf("Distance: %.1f cm\n", distanceCm);
  }

  delay(500);
}
  1. 1Click Upload.
  2. 2If the IDE shows "Connecting........" and stalls, press and hold the BOOT button on the ESP32 until the upload starts, then let go. Many boards need this.
  3. 3When it says "Done uploading", open Tools > Serial Monitor and set the speed to 115200 baud. Press the board's EN (reset) button if the screen is empty.
  4. 4Move your hand toward and away from the sensor.
Output
Distance: 34.6 cm
Distance: 20.2 cm
Distance: 8.9 cm
No echo - nothing in range?

How the sketch works

The idea is the same on every board: pulse Trig for 10 µs, time how long Echo stays HIGH, divide by 58. Only three lines differ from the Arduino version.

Code explained

Serial.begin(115200);
Opens the serial link at 115200 baud, the usual ESP32 speed.
digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10);
Raises Trig for 10 µs: the "measure now" signal.
pulseIn(ECHO_PIN, HIGH, 30000UL);
Times how long Echo stays HIGH, in microseconds. Gives up after 30 ms and returns 0.
echoTime / 58.0
Turns microseconds into centimetres (out-and-back time at the speed of sound).
Serial.printf("%.1f", distanceCm);
ESP32 can format numbers with printf. %.1f means one decimal place.

Try this circuit in the SolderHub Simulator

Run this exact circuit in your browserReady-wired, code loaded

Confirm simulator behavior against the real wiring and the sensor datasheet before connecting hardware.

Experiments

Try these to learn the sensor's limits: point it at a wall, tilt a book to 45°, hold a pillow in front of it, and move your hand closer than 2 cm. The Arduino Uno guide explains what you should expect in each case; the picture below summarises it.

Why some surfaces work and others do not

Steadier readings and temperature correction

Readings can jump by a centimetre or two. This sketch takes five measurements and keeps the middle one, which throws away spikes. It also corrects for air temperature, because sound travels faster in warm air. Set airTempC to your room temperature, or feed it from a sensor such as a DS18B20.

HC-SR04 timing: trigger the sensor for at least 10 µs and measure the ECHO pulse width.
sketch.ino
// Steadier readings: median of 5, with optional temperature correction.
const int TRIG_PIN = 4;
const int ECHO_PIN = 18;
const int SAMPLES = 5;
float airTempC = 25.0;      // change this, or feed it from a temperature sensor

float readCm() {
  digitalWrite(TRIG_PIN, LOW);  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  unsigned long t = pulseIn(ECHO_PIN, HIGH, 30000UL);
  if (t == 0) return -1.0;
  float soundCmPerUs = (331.3 + 0.606 * airTempC) / 10000.0;
  return t * soundCmPerUs / 2.0;
}

float medianCm() {
  float v[SAMPLES];
  for (int i = 0; i < SAMPLES; i++) { v[i] = readCm(); delay(60); }
  for (int i = 1; i < SAMPLES; i++) {            // sort smallest to largest
    float key = v[i]; int j = i - 1;
    while (j >= 0 && v[j] > key) { v[j + 1] = v[j]; j--; }
    v[j + 1] = key;
  }
  return v[SAMPLES / 2];                          // the middle value
}

void setup() {
  Serial.begin(115200);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
}

void loop() {
  float cm = medianCm();
  if (cm < 0) Serial.println("No echo");
  else Serial.printf("%.1f cm (air %.0f C)\n", cm, airTempC);
}

Project. Put your sensor on the network

A sensor that talks to your phone feels very different from one that prints to a computer. This project takes three small steps. Each one works on its own, so stop wherever you are happy:

  • Part A connects the ESP32 to your Wi-Fi.
  • Part B turns it into a live dashboard on your phone: a big reading, a level meter, a 50-second graph and an alert. Everything runs inside the ESP32, with no cloud account and no internet needed.
  • Part C removes your Wi-Fi password from the code, so the board can be set up from a phone and moved to any network.

Part A. Connect to Wi-Fi

Wi-Fi gives your ESP32 an IP address on your home network, like a house number. Anything on the same network, such as your phone, can then talk to it. The ESP32 only joins 2.4 GHz networks. If your router has separate 2.4 and 5 GHz names, use the 2.4 GHz one.

Theoretical Echo pulse duration versus one-way distance at approximately 20 °C.
  1. 1Replace YOUR_WIFI_NAME and YOUR_WIFI_PASSWORD with your own. Keep the quotes, and remember that names and passwords are case sensitive.
  2. 2Upload the sketch and open the Serial Monitor at 115200 baud. Press the board's EN button if the screen is empty.
  3. 3Within a few seconds you should see "Connected!" and an IP address. Write the address down.
sketch.ino
// Step A: connect the ESP32 to your Wi-Fi and print its address.
#include <WiFi.h>

const char* WIFI_SSID = "YOUR_WIFI_NAME";
const char* WIFI_PASS = "YOUR_WIFI_PASSWORD";

void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);                 // station mode: join an existing network
  WiFi.begin(WIFI_SSID, WIFI_PASS);

  Serial.print("Connecting to ");
  Serial.println(WIFI_SSID);

  unsigned long start = millis();
  while (WiFi.status() != WL_CONNECTED) {
    if (millis() - start > 20000) {    // give up after 20 seconds
      Serial.println("\nCould not connect. Check the name, the password, and that it is 2.4 GHz.");
      return;
    }
    delay(500);
    Serial.print(".");
  }

  Serial.println("\nConnected!");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.print("Signal strength: ");
  Serial.print(WiFi.RSSI());
  Serial.println(" dBm");
}

void loop() {}
Output
Connecting to MyHomeWiFi
.....
Connected!
IP address: 192.168.1.42
Signal strength: -58 dBm

A signal around -30 to -60 dBm is strong, -70 is usable, and -80 or weaker will drop out. If yours is weak, move the board closer to the router.

If it will not connect

  • Dots forever, then a failure message

    Most likely cause
    Wrong password or name, or a 5 GHz-only network
    Fix
    Retype both carefully and make sure the 2.4 GHz band is on.
  • Connects, but your phone cannot open the page

    Most likely cause
    Guest network or AP isolation on the router
    Fix
    Put the phone and the ESP32 on the main network.
  • Works, then drops after a while

    Most likely cause
    Weak signal or a weak USB supply
    Fix
    Move closer to the router and use a good USB cable.

Part B. Live dashboard on your phone

Upload this sketch with your Wi-Fi details filled in. When it connects, open the address it prints, or type distance.local into your phone's browser. If distance.local does not load (some Android phones cannot resolve .local names), use the IP address from the Serial Monitor instead.

sketch.ino
// Step B: live distance dashboard. Open http://distance.local (or the IP address).
#include <WiFi.h>
#include <WebServer.h>
#include <ESPmDNS.h>

const char* WIFI_SSID = "YOUR_WIFI_NAME";
const char* WIFI_PASS = "YOUR_WIFI_PASSWORD";

const int TRIG_PIN = 4;
const int ECHO_PIN = 18;

WebServer server(80);

// The whole web page lives inside the ESP32. No internet needed.
const char PAGE[] = R"HTML(
<!doctype html><html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Distance</title>
<style>
:root{--bg:#fff;--fg:#0f172a;--mut:#64748b;--card:#f1f5f9;--ok:#16a34a}
@media(prefers-color-scheme:dark){:root{--bg:#0b1220;--fg:#e2e8f0;--mut:#94a3b8;--card:#162033}}
body{margin:0;font-family:system-ui,sans-serif;background:var(--bg);color:var(--fg);text-align:center;transition:background .3s}
body.alert{background:#7f1d1d;color:#fff}
main{max-width:520px;margin:0 auto;padding:16px}
.big{font-size:22vw;font-weight:800;line-height:1}
@media(min-width:600px){.big{font-size:110px}}
.card{background:var(--card);border-radius:14px;padding:12px;margin:12px 0}
body.alert .card{background:#991b1b}
.bar{height:14px;border-radius:7px;background:#cbd5e1;overflow:hidden}
#fill{height:100%;width:0;background:var(--ok);transition:width .3s}
canvas{width:100%;height:120px}
.row{display:flex;gap:8px;justify-content:space-between;flex-wrap:wrap}
label{font-size:13px;color:var(--mut)}body.alert label{color:#fecaca}
input{width:64px;font-size:16px}
</style></head><body><main>
<p style="color:var(--mut)">Distance</p>
<div class="big" id="cm">--</div><div style="color:var(--mut)">centimetres</div>
<div class="card"><div class="bar"><div id="fill"></div></div><div id="lvl" style="margin-top:6px">Set empty and full below for a level meter</div></div>
<div class="card"><canvas id="c" width="480" height="120"></canvas>
<div class="row"><span>min <b id="mn">--</b></span><span>last 50 s</span><span>max <b id="mx">--</b></span></div></div>
<div class="card">
<div class="row"><label>Empty at <input id="e" type="number" value="100"> cm</label><label>Full at <input id="f" type="number" value="10"> cm</label></div>
<div class="row" style="margin-top:8px"><label>Alert when closer than <input id="a" type="number" value="0"> cm</label></div>
</div></main>
<script>
const $ = id => document.getElementById(id);
const N = 125, H = [];
for (const k of ['e','f','a']) {                    // remember settings in this browser
  const v = localStorage.getItem('hc' + k);
  if (v) $(k).value = v;
  $(k).onchange = () => localStorage.setItem('hc' + k, $(k).value);
}
function draw() {
  const c = $('c'), x = c.getContext('2d');
  x.clearRect(0, 0, c.width, c.height);
  const v = H.filter(n => n !== null);
  if (v.length < 2) return;
  const lo = Math.min(...v), hi = Math.max(...v), r = Math.max(hi - lo, 5);
  x.strokeStyle = '#2563eb'; x.lineWidth = 2; x.beginPath();
  let pen = false;
  H.forEach((n, i) => {
      if (n === null) { pen = false; return; }
      const X = i / (N - 1) * c.width, Y = c.height - 6 - (n - lo) / r * (c.height - 12);
      if (pen) x.lineTo(X, Y); else { x.moveTo(X, Y); pen = true; }
  });
  x.stroke();
}
async function tick() {
  let cm = null;
  try { cm = (await (await fetch('/api')).json()).cm; } catch (e) {}
  if (cm !== null && cm < 0) cm = null;             // -1 means "no echo"
  H.push(cm); if (H.length > N) H.shift();
  $('cm').textContent = cm === null ? '--' : cm.toFixed(1);
  const v = H.filter(n => n !== null);
  $('mn').textContent = v.length ? Math.min(...v).toFixed(1) : '--';
  $('mx').textContent = v.length ? Math.max(...v).toFixed(1) : '--';
  const e = +$('e').value, f = +$('f').value;
  if (cm !== null && e !== f) {
    const p = Math.max(0, Math.min(100, (e - cm) / (e - f) * 100));
    $('fill').style.width = p + '%';
    $('lvl').textContent = 'Level ' + Math.round(p) + '%';
  }
  const a = +$('a').value, hot = cm !== null && a > 0 && cm < a;
  document.body.classList.toggle('alert', hot);
  if (hot && navigator.vibrate) navigator.vibrate(100);
  draw();
}
setInterval(tick, 400); tick();
</script></body></html>
)HTML";

float readCm() {
  digitalWrite(TRIG_PIN, LOW);  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  unsigned long t = pulseIn(ECHO_PIN, HIGH, 30000UL);
  return t == 0 ? -1.0 : t / 58.0;
}

// Many phones can open the page at once, but the sensor needs 60 ms between
// measurements. So we measure at most every 100 ms and share the answer.
float cachedCm = -1.0;
unsigned long lastRead = 0;
float latestCm() {
  if (millis() - lastRead >= 100) { cachedCm = readCm(); lastRead = millis(); }
  return cachedCm;
}

void handleRoot() { server.send(200, "text/html", PAGE); }

void handleApi() {
  String json = "{\"cm\":" + String(latestCm(), 1) + "}";
  server.sendHeader("Cache-Control", "no-store");
  server.send(200, "application/json", json);
}

void setup() {
  Serial.begin(115200);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);

  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); }

  Serial.print("\nOpen http://");
  Serial.println(WiFi.localIP());
  if (MDNS.begin("distance")) Serial.println("Or open http://distance.local");

  server.on("/", handleRoot);
  server.on("/api", handleApi);
  server.begin();
}

void loop() {
  server.handleClient();
}

What you get on the page:

  • A large live reading that updates about twice a second.
  • A level meter. Tell it the distance when empty and when full, and it shows a percentage.
  • A 50-second graph with minimum and maximum, so you can see a trend, not just a number.
  • An alert. Type a distance, and the page turns red (and vibrates a phone) when something comes closer than that.
  • Saved settings. Your numbers are remembered in the phone's browser.

How it works, in three ideas

  1. The page lives inside the ESP32. The big block of text between R"HTML( and )HTML" is a complete web page stored in the sketch. When your phone opens the address, the ESP32 sends it once.
  2. The page asks for numbers. A few lines of JavaScript call the address /api every 400 ms. The ESP32 answers with a tiny message like {"cm":23.4}, and the page draws it.
  3. The sensor is shared. Two phones could open the page at once, but the sensor needs 60 ms between measurements. So latestCm() measures at most every 100 ms and hands the same answer to everyone.

Make it a water tank level meter

This is what the empty and full boxes are for.

  1. Fix the sensor on the tank lid, pointing straight down at the water.
  2. With the tank empty, read the distance on the page and type it into Empty at.
  3. Fill the tank and type the new distance into Full at. Keep the full level at least 5 cm below the sensor, because the sensor cannot measure closer than 2 cm and works best with a clear gap.
  4. The level bar now shows how full the tank is.

Keep the sensor itself dry. The module is not waterproof, and condensation on a closed tank can damage it. For a damp tank, use a waterproof probe such as the JSN-SR04T.

Part C. No more hard-coded password

Writing your Wi-Fi password into the code is fine for learning, but awkward for a finished device. This sketch makes the ESP32 behave like a commercial smart gadget:

  1. The first time it starts, it has no saved network, so it creates its own Wi-Fi called HC-SR04-Setup.
  2. You join that Wi-Fi from your phone. A setup page opens (or go to 192.168.4.1).
  3. You type your home Wi-Fi name and password once. The ESP32 saves them in its own memory and restarts.
  4. From then on it connects by itself. To forget the network, hold the BOOT button while powering on.
sketch.ino
// Step C: no hard-coded password. The ESP32 opens its own setup Wi-Fi the first time.
// Hold the BOOT button while powering on to forget the saved network.
#include <WiFi.h>
#include <WebServer.h>
#include <DNSServer.h>
#include <Preferences.h>

Preferences prefs;
WebServer server(80);
DNSServer dns;

const char FORM[] = R"HTML(
<!doctype html><html><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1"><title>Wi-Fi setup</title></head>
<body style="font-family:sans-serif;max-width:420px;margin:30px auto;padding:0 16px">
<h2>Connect your sensor to Wi-Fi</h2>
<form action="/save" method="post">
<p><input name="s" placeholder="Wi-Fi name" style="width:100%;padding:10px;font-size:16px"></p>
<p><input name="p" type="password" placeholder="Password" style="width:100%;padding:10px;font-size:16px"></p>
<p><button style="padding:10px 18px;font-size:16px">Save and connect</button></p>
</form></body></html>
)HTML";

bool connectSaved() {
  String ssid = prefs.getString("ssid", "");
  if (ssid == "") return false;
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid.c_str(), prefs.getString("pass", "").c_str());
  unsigned long t = millis();
  while (WiFi.status() != WL_CONNECTED && millis() - t < 15000) delay(250);
  return WiFi.status() == WL_CONNECTED;
}

void startPortal() {
  WiFi.mode(WIFI_AP);
  WiFi.softAP("HC-SR04-Setup");                       // open network, only used for setup
  dns.start(53, "*", WiFi.softAPIP());                // send every address to this page
  server.on("/", []() { server.send(200, "text/html", FORM); });
  server.on("/save", HTTP_POST, []() {
      prefs.putString("ssid", server.arg("s"));
      prefs.putString("pass", server.arg("p"));
      server.send(200, "text/html", "<h3>Saved. The sensor is restarting...</h3>");
      delay(1000);
      ESP.restart();
  });
  server.onNotFound([]() {
      server.sendHeader("Location", "http://192.168.4.1/", true);
      server.send(302, "text/plain", "");
  });
  server.begin();
  Serial.println("Join the Wi-Fi called HC-SR04-Setup, then open http://192.168.4.1");
  while (true) { dns.processNextRequest(); server.handleClient(); delay(2); }
}

void setup() {
  Serial.begin(115200);
  pinMode(0, INPUT_PULLUP);                           // BOOT button
  prefs.begin("wifi", false);
  if (digitalRead(0) == LOW) prefs.clear();           // held at power-on: forget network

  if (connectSaved()) {
    Serial.print("Connected. IP address: ");
    Serial.println(WiFi.localIP());
  } else {
    startPortal();
  }
}

void loop() {}

To combine Part B and Part C, copy the connectSaved() and startPortal() functions and the setup code into the dashboard sketch, and use them instead of the hard-coded WiFi.begin(...) lines. The saved name and password are stored in Preferences, a small key-value store built into the ESP32.

Ideas to build on this

  • Home Assistant or MQTT. Publish the distance so other devices and automations can use it.
  • Over-the-air updates. Add ArduinoOTA so you can upload new code over Wi-Fi without a cable.
  • Battery power. Wake the ESP32 every few minutes with deep sleep, measure, send, and sleep again.

Troubleshooting

Fix it fast

  • Always "No echo"

    Most likely cause
    Wiring, or VCC on 3V3 instead of VIN
    Fix
    Compare to the wiring table. VCC must go to VIN (5V).
  • Upload stalls at "Connecting..."

    Most likely cause
    Board is not entering upload mode
    Fix
    Hold the BOOT button during upload.
  • No port in the Port menu

    Most likely cause
    Charge-only cable or missing driver
    Fix
    Use a data cable. Install the CP210x or CH340 driver.
  • Board resets when the sensor starts

    Most likely cause
    Weak USB port or cable causing a brownout
    Fix
    Use a better cable or a powered USB port. Add a 100 µF capacitor across VCC and GND.
  • Readings stuck very small

    Most likely cause
    Divider wired wrongly, or something in front of the sensor
    Fix
    Check the 2 kΩ goes to GND and GPIO18 connects at the junction.
  • Distances are always too large or too small

    Most likely cause
    Resistor values swapped
    Fix
    1 kΩ goes between Echo and the junction, 2 kΩ between the junction and GND.
  • Web page does not load

    Most likely cause
    Phone on a different network, or 5 GHz Wi-Fi
    Fix
    Join the same 2.4 GHz network and check the IP address.
ESP32 troubleshooting: common symptoms, likely causes and fixes

Where to go next

  • Read the HC-SR04 overview for range, angle and temperature details.
  • Build the Uno version with a buzzer and servo in the Arduino Uno guide.
  • Log the readings online, or trigger an alert when something comes closer than a set distance.

Technical references

Keep learning

Related guides & projects