The classic Arduino radar usually ends with a sensor stuttering from one angle to the next and a graph on a PC. This build goes further: an ESP32 sweeps an HC-SR04 ultrasonic sensor on an SG90 servo in one smooth motion, serves a live radar screen to any phone or laptop on your Wi-Fi, draws a mini radar on a 1.3-inch OLED, and beeps a buzzer faster as something gets closer. There's no app, no cloud service and no PC needed once it's flashed.
Three things cause most of the trouble with this project: powering the servo from the wrong place, connecting the sensor's 5V ECHO pin straight to the ESP32, and running everything in one loop so the servo, sensor and web server get in each other's way. This guide handles all three, one step at a time.
What You're Actually Building
The servo swings the sensor from 15° to 165° and back, taking about 3 seconds each way. While it moves, the ESP32 fires an ultrasonic ping about 14 times a second and pairs each distance with the current angle. Those readings go to three places:
- The web dashboard: a green sweep line with a fading trail, range rings out to 100 cm, and red blips that fade after 5 seconds. Open the ESP32's IP address in any browser on the same network.
- The OLED: a small version of the radar with the current distance and angle. It also shows the IP address at startup, so you don't need the Serial Monitor to find it.
- The buzzer: silent until something comes within 50 cm, then beeping faster as the object gets closer.
If your router isn't available, the ESP32 creates its own Wi-Fi network called ESP32-Radar, which is handy for demos away from home.
How It Works, Start to Finish
- Startup: the ESP32 starts the OLED, connects to Wi-Fi, and starts the web server. Only then does it attach the servo and start the background tasks.
- Sweep: the servo follows a smooth curve from 15° to 165° and back.
- Ping: about 14 times a second, the ESP32 sends a 10 microsecond pulse to TRIG. The HC-SR04 sends out an ultrasonic burst and holds ECHO high until the sound returns.
- Measure: the ESP32 times that ECHO pulse. Distance is
time × 0.0343 ÷ 2, because sound travels about 0.0343 cm per microsecond and makes a round trip. - Filter: the code takes the middle value of the last three pings, which removes one-off false echoes. Anything beyond 100 cm is ignored.
- Store: each valid angle and distance goes into a small queue in memory that holds the latest 64 readings.
- Display: the browser collects new readings every 100 ms and draws them as red blips. The OLED draws its own mini radar, and the buzzer checks the nearest distance and beeps faster as it gets closer.
Before You Start
This is a good project even if you've never used an ESP32, because you can copy all of the code. Allow about 1 to 2 hours for your first build.
- You will need: a computer with Arduino IDE installed, and the parts in the list below.
- Go in order: finish each step before starting the next one. Most problems come from skipping a step or from one loose wire.
- Stuck on a word? There's a short list of terms near the end of this guide.
- Always unplug USB before moving any wire.
How the Code Stays Smooth
You don't need to understand this section to build the radar, so feel free to skip it. In short, the ESP32 has two processor cores, and the code splits the work into small separate jobs called tasks. Think of them as workers who each do one job, so one slow worker can't hold up the others:
| Task | Core | Job |
|---|---|---|
| Motion | 1 | Moves the servo along a smooth curve, independent of everything else |
| Sensor | 0 | Fires pings and filters out one-off false echoes |
| Web | 0 | Serves the page and the /data readings |
| OLED | 0 | Redraws the mini radar 10 times a second |
| Buzzer | 0 | Beeps according to the nearest distance |
The servo's position is calculated from time using a cosine curve, instead of being stepped degree by degree. That removes the stop-and-go jerk and slows the servo gently at each end of the sweep.
The browser uses the same curve to draw the sweep line, so the line stays smooth at your screen's full refresh rate. Readings are queued on the ESP32 and collected by the page every 100 ms, so none are lost between requests.
Hardware You'll Need
| Item | Notes |
|---|---|
| ESP32 DevKit (WROOM-32) | 30 or 38 pin, selected as ESP32 Dev Module |
| HC-SR04 ultrasonic sensor | Needs 5V to run |
| SG90 micro servo | Clones work too |
| Sensor bracket | 3D printed, acrylic pan bracket, or hot glue on the servo horn |
| 1.3-inch I2C OLED (SH1106) | 4-pin module, optional |
| Active buzzer (3.3V type) | Beeps by itself when powered |
| 1 kΩ and 2 kΩ resistors | Voltage divider for ECHO |
| External 5V supply | For the servo, 1 A or more |
| 470 µF capacitor | Across the servo's power, recommended |
| Breadboard, jumper wires, USB data cable | Some USB cables only carry power |
Step 1: Wire the Circuit
Unplug the ESP32 from USB before you connect anything. On most boards the pins are labelled D5, D18 and so on, which are the same pins the code calls GPIO5 and GPIO18. Use this table as your reference, then follow the numbered steps below it, wiring one part at a time:
| Part | Pin | Connect to |
|---|---|---|
| HC-SR04 | VCC | VIN (5V while on USB) |
| HC-SR04 | GND | GND |
| HC-SR04 | TRIG | GPIO5 (D5) |
| HC-SR04 | ECHO | 1 kΩ resistor, then GPIO18 (D18) |
| Divider | 2 kΩ resistor | From GPIO18 to GND |
| SG90 | Orange (signal) | GPIO15 (D15) |
| SG90 | Red (power) | External 5V |
| SG90 | Brown (ground) | External supply GND |
| External supply | GND | ESP32 GND |
| OLED | VCC | 3V3 |
| OLED | GND | GND |
| OLED | SDA | GPIO21 (D21) |
| OLED | SCL | GPIO22 (D22) |
| Buzzer | + | GPIO4 (D4) |
| Buzzer | - | GND |
Read the labels on your OLED rather than trusting pin position, because many 1.3-inch modules swap VCC and GND.
Steps
- 1Press the ESP32 into the middle of the breadboard so its two rows of pins sit on either side of the centre gap.
- 2Connect an ESP32 GND pin to the breadboard's blue (-) rail. Every GND connection below can go to this rail.
- 3Connect the HC-SR04: VCC to VIN, GND to the blue rail, and TRIG to D5.
- 4Build the voltage divider. Connect the HC-SR04 ECHO pin to one leg of the 1 kΩ resistor, and connect the other leg to D18. Then connect the 2 kΩ resistor between D18 and the blue rail.
- 5Connect the OLED: VCC to 3V3, GND to the blue rail, SDA to D21 and SCL to D22. Read the labels on your own module.
- 6Connect the buzzer: + to D4 and - to the blue rail. On a buzzer with wire legs, the longer leg is usually +.
- 7Connect the servo signal wire (orange) to D15.
- 8Connect the servo power: red to the external 5V supply and brown to that supply's negative or GND.
- 9Connect the external supply's negative or GND to the blue rail. The radar won't work properly without this shared ground.
- 10Compare every wire against the table above before you plug in USB.
Step 2: Mount the Sensor on the Servo
- Before fixing the horn, power the servo briefly or turn it by hand gently to find the middle of its travel.
- Attach the horn and bracket so the sensor faces straight ahead at the middle position.
- Fix the sensor firmly. A loose sensor vibrates and gives noisy readings.
- Leave enough slack in the sensor wires to reach both ends of the sweep without pulling.
- Keep wires and the bracket out of the front of the sensor, or it will detect them as objects.
Step 3: Set Up the Arduino IDE
- Open File → Preferences, and in "Additional Board Manager URLs" add:
https://espressif.github.io/arduino-esp32/package_esp32_index.json - Open Tools → Board → Boards Manager, search for
esp32, and install esp32 by Espressif Systems. - Open Sketch → Include Library → Manage Libraries and install ESP32Servo, Adafruit SH110X and Adafruit GFX Library. Accept any extra libraries it offers, such as Adafruit BusIO.
- Select Tools → Board → ESP32 Arduino → ESP32 Dev Module.
- Connect the board with a USB data cable and choose its port under Tools → Port. If no port appears, install the CP210x or CH340 USB driver for your board.
Step 4: Add the Code
You don't need to write any code. You only copy it and change two lines:
- In Arduino IDE, click File → New Sketch.
- Click inside the new window, press Ctrl + A to select everything, then press Delete.
- Copy the full code below and paste it into the empty window.
- Near the top, find
WIFI_SSIDandWIFI_PASS, and type your Wi-Fi name and password between the quote marks. Keep the quote marks, and match capital and small letters exactly. - Press Ctrl + S to save, and give the sketch a name such as
esp32_radar.
For example, if your Wi-Fi is called HomeNet and the password is mypassword123, the two lines look like this:
const char* WIFI_SSID = "HomeNet";
const char* WIFI_PASS = "mypassword123";The ESP32 can only join 2.4 GHz Wi-Fi networks. If your router has separate 2.4 GHz and 5 GHz names, use the 2.4 GHz one. You can also download the code from the SolderHub projects repository.
Station Mode and Access Point Mode
The ESP32's Wi-Fi can work in two main ways, and this project uses both.
Station mode (WIFI_STA) is the normal mode. The ESP32 joins your router like a phone or laptop does, and your router gives it an IP address such as 192.168.1.50. Any device on the same network can open the radar, and the code tries this first.
Access Point mode (WIFI_AP) makes the ESP32 create its own Wi-Fi network. If it can't join your router within 15 seconds, it switches to this mode automatically and creates a network called ESP32-Radar, with the password radar1234. Connect your phone to that network and open http://192.168.4.1. The OLED shows these details too.
Your phone won't have internet access while it's connected to ESP32-Radar, but the radar page will still work because the ESP32 serves it directly.
// ================================================================
// ESP32 Ultrasonic Radar: smooth sweep, web dashboard, 1.3" OLED
//
// SolderHub | https://solderhub.com
// A community for electronics enthusiasts and makers.
// Step-by-step guide:
// https://solderhub.com/projects/esp32-servo-ultrasonic-radar-web-dashboard
// Source code: https://github.com/solderhubofficial/projects
//
// Board: ESP32 Dev Module (WROOM-32)
// Sensor: HC-SR04 Servo: SG90 Display: SH1106 1.3" I2C (optional)
// Libraries: ESP32Servo, Adafruit SH110X, Adafruit GFX
//
// Wiring
// HC-SR04 VCC -> 5V (VIN) GND -> GND
// HC-SR04 TRIG -> GPIO5
// HC-SR04 ECHO -> 1k -> GPIO18, and 2k from GPIO18 to GND
// SG90 orange -> GPIO15 red -> external 5V
// SG90 brown -> external GND, tied to ESP32 GND
// OLED VCC -> 3V3 GND -> GND SDA -> GPIO21 SCL -> GPIO22
// Active buzzer + -> GPIO4 - -> GND
// ================================================================
#include <WiFi.h>
#include <WebServer.h>
#include <ESP32Servo.h>
#include <esp_system.h>
#define USE_OLED 1 // Set to 0 to build without the display
#if USE_OLED
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SH110X.h>
#endif
// ---------- Edit these ----------
const char* WIFI_SSID = "YOUR_WIFI_SSID";
const char* WIFI_PASS = "YOUR_WIFI_PASSWORD";
// If the router can't be reached, the ESP32 creates this network instead.
const char* AP_SSID = "ESP32-Radar";
const char* AP_PASS = "radar1234";
const uint32_t SWEEP_ONE_WAY_MS = 3000; // Higher = slower and smoother
const int SWEEP_MIN = 15; // degrees
const int SWEEP_MAX = 165; // degrees
const float MAX_CM = 100; // Radar's outer ring
const bool FLIP_DISPLAY = false; // true if left and right look swapped
const float BUZZER_ALERT_CM = 50; // Beeps inside this range, 0 = silent
// --------------------------------
const int TRIG_PIN = 5;
const int ECHO_PIN = 18;
const int SERVO_PIN = 15;
const int BUZZER_PIN = 4;
const int OLED_SDA = 21;
const int OLED_SCL = 22;
const uint8_t OLED_ADDR = 0x3C;
const int SERVO_MIN_US = 500;
const int SERVO_MAX_US = 2400;
const uint32_t SERVO_FRAME_MS = 20; // The servo only accepts 50 updates a second
const uint32_t PING_MS = 70; // Gives each echo time to die away
const unsigned long ECHO_TIMEOUT_US = 30000;
const float NO_ECHO = 9999;
const uint32_t SWEEP_PERIOD_MS = 2 * SWEEP_ONE_WAY_MS;
const float SWEEP_MID = (SWEEP_MIN + SWEEP_MAX) / 2.0f;
const float SWEEP_AMP = (SWEEP_MAX - SWEEP_MIN) / 2.0f;
struct Reading {
float angle;
float cm;
};
const int RING_SIZE = 64;
Reading ring[RING_SIZE];
uint32_t ringSeq = 0;
float latestCm = -1;
portMUX_TYPE ringMux = portMUX_INITIALIZER_UNLOCKED;
uint32_t sweepStart = 0;
Servo radarServo;
WebServer server(80);
uint32_t sweepMs() {
return millis() - sweepStart;
}
// Position is a smooth cosine of time: no stop-and-go, and gentle reversals.
float angleAt(uint32_t t) {
float phase = float(t % SWEEP_PERIOD_MS) / SWEEP_PERIOD_MS;
return SWEEP_MID - SWEEP_AMP * cos(TWO_PI * phase);
}
int angleToMicros(float angle) {
return SERVO_MIN_US + angle / 180.0f * (SERVO_MAX_US - SERVO_MIN_US);
}
// Highest priority, fixed rate, so nothing else can make the servo stutter.
void motionTask(void*) {
TickType_t wake = xTaskGetTickCount();
for (;;) {
vTaskDelayUntil(&wake, pdMS_TO_TICKS(SERVO_FRAME_MS));
radarServo.writeMicroseconds(angleToMicros(angleAt(sweepMs())));
}
}
float pingCm() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
unsigned long us = pulseIn(ECHO_PIN, HIGH, ECHO_TIMEOUT_US);
if (us == 0) return NO_ECHO;
float cm = us * 0.0343f / 2.0f;
return (cm < 2 || cm > MAX_CM) ? NO_ECHO : cm;
}
float median3(float a, float b, float c) {
return max(min(a, b), min(max(a, b), c));
}
void sensorTask(void*) {
float cm[3] = {NO_ECHO, NO_ECHO, NO_ECHO};
float angle[3] = {SWEEP_MIN, SWEEP_MIN, SWEEP_MIN};
TickType_t wake = xTaskGetTickCount();
for (;;) {
vTaskDelayUntil(&wake, pdMS_TO_TICKS(PING_MS));
cm[0] = cm[1];
cm[1] = cm[2];
angle[0] = angle[1];
angle[1] = angle[2];
angle[2] = angleAt(sweepMs());
cm[2] = pingCm();
// A median of 3 removes one-off ghost echoes. It describes the middle ping.
float filtered = median3(cm[0], cm[1], cm[2]);
bool valid = filtered < NO_ECHO;
portENTER_CRITICAL(&ringMux);
latestCm = valid ? filtered : -1;
if (valid) {
ring[ringSeq % RING_SIZE] = {angle[1], filtered};
ringSeq++;
}
portEXIT_CRITICAL(&ringMux);
}
}
// Copies readings newer than `since`, then moves `since` forward.
int copyReadings(uint32_t& since, Reading* out, float* latest) {
int count = 0;
portENTER_CRITICAL(&ringMux);
if (since > ringSeq) since = 0;
if (ringSeq - since > RING_SIZE) since = ringSeq - RING_SIZE;
while (since < ringSeq) {
out[count++] = ring[since % RING_SIZE];
since++;
}
if (latest) *latest = latestCm;
portEXIT_CRITICAL(&ringMux);
return count;
}
const char INDEX_HTML[] PROGMEM = R"HTMLPAGE(
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ESP32 Radar</title>
<style>
body{background:#0b0f0b;color:#39ff14;font-family:monospace;text-align:center;margin:0;padding:16px;}
h1{font-size:20px;letter-spacing:2px;margin:4px 0;}
#readout{font-size:16px;margin:10px 0;color:#7dffb3;}
#link{font-size:12px;margin:8px 0;color:#7dffb3;}
canvas{background:#040704;border:2px solid #1a3d1a;border-radius:8px;max-width:100%;height:auto;}
</style>
</head>
<body>
<h1>ESP32 RADAR</h1>
<div id="readout">ANGLE: -- ° DIST: -- cm</div>
<canvas id="radar" width="600" height="320"></canvas>
<div id="link">CONNECTING</div>
<script>
const canvas = document.getElementById('radar');
const ctx = canvas.getContext('2d');
const cx = 300, cy = 310, R = 290, BLIP_MS = 5000, TRAIL = 32, TRAIL_STEP = 25;
let cfg = null, since = 0, clockOffset = null, blips = [], latest = -1;
function angleAt(t){
const p = cfg.period, u = ((t % p) + p) % p;
return cfg.mid - cfg.amp * Math.cos(2 * Math.PI * u / p);
}
function point(deg, r){
const a = deg * Math.PI / 180, s = cfg.flip ? -1 : 1;
return [cx - s * r * Math.cos(a), cy - r * Math.sin(a)];
}
function line(deg, color, width){
const p = point(deg, R);
ctx.strokeStyle = color;
ctx.lineWidth = width;
ctx.beginPath();
ctx.moveTo(cx, cy);
ctx.lineTo(p[0], p[1]);
ctx.stroke();
}
function drawGrid(){
ctx.strokeStyle = '#1a3d1a';
ctx.lineWidth = 1;
ctx.fillStyle = '#3f8f3f';
ctx.font = '11px monospace';
for(let i = 1; i <= 4; i++){
const r = R * i / 4;
ctx.beginPath();
ctx.arc(cx, cy, r, Math.PI, 2 * Math.PI);
ctx.stroke();
ctx.fillText(Math.round(cfg.maxCm * i / 4) + 'cm', cx + 4, cy - r + 12);
}
for(let a = 0; a <= 180; a += 30) line(a, '#1a3d1a', 1);
}
function drawBlips(now){
blips = blips.filter(b => now - b.t < BLIP_MS);
blips.forEach(b => {
const p = point(b.a, Math.min(b.d / cfg.maxCm, 1) * R);
ctx.fillStyle = `rgba(255,60,60,${1 - (now - b.t) / BLIP_MS})`;
ctx.beginPath();
ctx.arc(p[0], p[1], 4, 0, 2 * Math.PI);
ctx.fill();
});
}
function drawSweep(t){
for(let k = TRAIL; k > 0; k--){
line(angleAt(t - k * TRAIL_STEP), `rgba(57,255,20,${0.28 * (1 - k / TRAIL)})`, 3);
}
line(angleAt(t), 'rgba(57,255,20,0.95)', 3);
}
function render(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
if(cfg){
const now = performance.now(), t = now + clockOffset, angle = angleAt(t);
drawGrid();
drawBlips(now);
drawSweep(t);
document.getElementById('readout').innerHTML =
'ANGLE: ' + angle.toFixed(0) + '° DIST: ' +
(latest < 0 ? '--' : latest.toFixed(1)) + ' cm';
}
requestAnimationFrame(render);
}
render();
async function poll(){
let wait = 100;
try{
const j = await (await fetch('/data?since=' + since)).json();
const now = performance.now(), offset = j.t - now;
cfg = j;
since = j.seq;
latest = j.d;
clockOffset = (clockOffset === null || Math.abs(offset - clockOffset) > 2000)
? offset : clockOffset + (offset - clockOffset) * 0.1;
j.r.forEach(r => blips.push({a: r[0], d: r[1], t: now}));
document.getElementById('link').textContent = 'LIVE';
}catch(e){
document.getElementById('link').textContent = 'CONNECTION LOST, RETRYING';
wait = 500;
}
setTimeout(poll, wait);
}
poll();
</script>
</body>
</html>
)HTMLPAGE";
void handleRoot() {
server.send_P(200, "text/html", INDEX_HTML);
}
void handleData() {
uint32_t since = strtoul(server.arg("since").c_str(), nullptr, 10);
Reading readings[RING_SIZE];
float latest = -1;
int count = copyReadings(since, readings, &latest);
String json;
json.reserve(180 + count * 14);
json += "{\"t\":";
json += sweepMs();
json += ",\"seq\":";
json += since;
json += ",\"period\":";
json += SWEEP_PERIOD_MS;
json += ",\"mid\":";
json += String(SWEEP_MID, 1);
json += ",\"amp\":";
json += String(SWEEP_AMP, 1);
json += ",\"maxCm\":";
json += String(MAX_CM, 0);
json += ",\"flip\":";
json += FLIP_DISPLAY ? "true" : "false";
json += ",\"d\":";
json += String(latest, 1);
json += ",\"r\":[";
for (int i = 0; i < count; i++) {
if (i) json += ',';
json += '[';
json += String(readings[i].angle, 1);
json += ',';
json += String(readings[i].cm, 1);
json += ']';
}
json += "]}";
server.send(200, "application/json", json);
}
// Web requests run on core 0, away from the servo and sensor tasks on core 1.
void webTask(void*) {
for (;;) {
server.handleClient();
vTaskDelay(pdMS_TO_TICKS(2));
}
}
// Beeps faster as the nearest object gets closer.
void buzzerTask(void*) {
for (;;) {
portENTER_CRITICAL(&ringMux);
float cm = latestCm;
portEXIT_CRITICAL(&ringMux);
if (cm > 0 && cm <= BUZZER_ALERT_CM) {
digitalWrite(BUZZER_PIN, HIGH);
vTaskDelay(pdMS_TO_TICKS(40));
digitalWrite(BUZZER_PIN, LOW);
vTaskDelay(pdMS_TO_TICKS(60 + cm / BUZZER_ALERT_CM * 440));
} else {
vTaskDelay(pdMS_TO_TICKS(50));
}
}
}
#if USE_OLED
const int OLED_CX = 64, OLED_CY = 63, OLED_R = 60;
const uint32_t OLED_FRAME_MS = 100;
const uint32_t OLED_BLIP_MS = 4000;
const int OLED_BUCKETS = 46; // One per 4 degrees
Adafruit_SH1106G display(128, 64, &Wire, -1);
bool oledReady = false;
uint32_t oledSince = 0;
uint32_t oledHoldUntil = 0;
float bucketCm[OLED_BUCKETS];
uint32_t bucketAt[OLED_BUCKETS];
void oledText(const char* a, const String& b, const String& c) {
if (!oledReady) return;
display.clearDisplay();
display.setCursor(0, 8);
display.println(a);
display.setCursor(0, 28);
display.println(b);
display.setCursor(0, 44);
display.println(c);
display.display();
}
void oledPoint(float angle, float radius, int& x, int& y) {
float a = radians(angle);
int side = FLIP_DISPLAY ? -1 : 1;
x = OLED_CX - side * radius * cos(a);
y = OLED_CY - radius * sin(a);
}
void updateOled() {
static uint32_t lastFrame = 0;
uint32_t now = millis();
if (!oledReady || int32_t(now - oledHoldUntil) < 0 || now - lastFrame < OLED_FRAME_MS) return;
lastFrame = now;
Reading fresh[RING_SIZE];
float latest = -1;
int count = copyReadings(oledSince, fresh, &latest);
for (int i = 0; i < count; i++) {
int bucket = constrain(int(fresh[i].angle / 4), 0, OLED_BUCKETS - 1);
bucketCm[bucket] = fresh[i].cm;
bucketAt[bucket] = now;
}
float angle = angleAt(sweepMs());
display.clearDisplay();
display.drawCircleHelper(OLED_CX, OLED_CY, OLED_R, 0x3, SH110X_WHITE);
display.drawCircleHelper(OLED_CX, OLED_CY, OLED_R / 2, 0x3, SH110X_WHITE);
int x, y;
oledPoint(angle, OLED_R, x, y);
display.drawLine(OLED_CX, OLED_CY, x, y, SH110X_WHITE);
for (int i = 0; i < OLED_BUCKETS; i++) {
if (bucketAt[i] == 0 || now - bucketAt[i] > OLED_BLIP_MS) continue;
oledPoint(i * 4 + 2, bucketCm[i] / MAX_CM * OLED_R, x, y);
display.fillCircle(x, y, 1, SH110X_WHITE);
}
display.setCursor(0, 0);
if (latest < 0) {
display.print("--");
} else {
display.print(int(latest));
display.print("cm");
}
String deg = String(int(angle)) + "d";
display.setCursor(128 - deg.length() * 6, 0);
display.print(deg);
display.display();
}
// The OLED runs on core 0 because the servo task keeps core 1 busy.
void oledTask(void*) {
Wire.end();
Wire.begin(OLED_SDA, OLED_SCL); // Moves I2C interrupts to this core
for (;;) {
updateOled();
vTaskDelay(pdMS_TO_TICKS(10));
}
}
#endif
void showStatus(const char* a, const String& b, const String& c, uint32_t holdMs) {
Serial.printf("%s %s %s\n", a, b.c_str(), c.c_str());
#if USE_OLED
oledText(a, b, c);
oledHoldUntil = millis() + holdMs;
#endif
}
void startNetwork() {
WiFi.mode(WIFI_STA);
WiFi.setSleep(false); // Lower, steadier dashboard latency
WiFi.begin(WIFI_SSID, WIFI_PASS);
showStatus("Connecting WiFi", WIFI_SSID, "", 0);
uint32_t started = millis();
while (WiFi.status() != WL_CONNECTED && millis() - started < 15000) {
delay(250);
}
if (WiFi.status() == WL_CONNECTED) {
showStatus("Open in browser:", WiFi.localIP().toString(), "", 5000);
return;
}
WiFi.disconnect(true);
WiFi.mode(WIFI_AP);
WiFi.softAP(AP_SSID, AP_PASS);
showStatus("Own WiFi mode", String(AP_SSID) + " / " + AP_PASS,
WiFi.softAPIP().toString(), 8000);
}
void setup() {
Serial.begin(115200);
delay(200);
if (esp_reset_reason() == ESP_RST_BROWNOUT) {
Serial.println("Brownout reset: give the servo its own 5V supply.");
}
pinMode(TRIG_PIN, OUTPUT);
digitalWrite(TRIG_PIN, LOW);
pinMode(ECHO_PIN, INPUT);
pinMode(BUZZER_PIN, OUTPUT);
digitalWrite(BUZZER_PIN, LOW);
#if USE_OLED
Wire.begin(OLED_SDA, OLED_SCL);
oledReady = display.begin(OLED_ADDR, true);
if (oledReady) {
display.setTextSize(1);
display.setTextColor(SH110X_WHITE);
showStatus("Starting radar", "", "", 0);
} else {
Serial.println("OLED not found, continuing without it.");
}
#endif
// Keep this order: Wi-Fi startup froze when it ran after the tasks below.
startNetwork();
server.on("/", handleRoot);
server.on("/data", handleData);
server.begin();
xTaskCreatePinnedToCore(webTask, "web", 8192, nullptr, 1, nullptr, 0);
ESP32PWM::allocateTimer(0);
radarServo.setPeriodHertz(50);
radarServo.attach(SERVO_PIN, SERVO_MIN_US, SERVO_MAX_US);
radarServo.writeMicroseconds(angleToMicros(SWEEP_MIN));
delay(700); // Let the servo reach the start before sweeping
sweepStart = millis();
xTaskCreatePinnedToCore(motionTask, "motion", 4096, nullptr, 3, nullptr, 1);
xTaskCreatePinnedToCore(sensorTask, "sensor", 4096, nullptr, 2, nullptr, 0); // Core 0: no pings ever completed on core 1
xTaskCreatePinnedToCore(buzzerTask, "buzzer", 2048, nullptr, 1, nullptr, 0);
#if USE_OLED
if (oledReady) xTaskCreatePinnedToCore(oledTask, "oled", 8192, nullptr, 1, nullptr, 0);
#endif
}
void loop() {
// All the work happens in the FreeRTOS tasks started in setup().
vTaskDelay(pdMS_TO_TICKS(1000));
}The Code in Short
| Part of the code | What it does |
|---|---|
| Edit these section | Your Wi-Fi details, sweep speed, radar range and buzzer range |
angleAt() | Works out where the servo should be at any moment |
motionTask() | Moves the servo to that position, 20 ms at a time |
pingCm() | Triggers the HC-SR04 and converts the echo time to centimetres |
sensorTask() | Pings regularly, filters the result and stores valid readings |
copyReadings() | Safely hands stored readings to the web page and OLED |
handleRoot() | Sends the dashboard page to the browser |
handleData() | Sends the latest readings to the browser as JSON |
buzzerTask() | Beeps faster as the nearest object gets closer |
updateOled() | Draws the mini radar, distance and angle on the OLED |
startNetwork() | Joins your Wi-Fi, or creates the ESP32's own network if that fails |
setup() | Starts everything in the correct order |
The loop() function is almost empty on purpose. Each job runs as its own task, so loop() has nothing left to do.
The HTML Dashboard Explained
The whole web page is stored inside the sketch as the INDEX_HTML text, so there are no separate files to upload. PROGMEM keeps it in flash memory rather than RAM.
The HTML is small: a title, a line showing the angle and distance, a 600 × 320 <canvas> where the radar is drawn, and a status line that shows LIVE when data is arriving.
The CSS sets the black and green radar look, and max-width:100% shrinks the radar to fit a phone screen.
The JavaScript does the drawing:
| Function | What it does |
|---|---|
angleAt(t) | Uses the same curve as the ESP32, so the sweep line matches the servo |
point(deg, r) | Converts an angle and distance into x and y positions on the canvas |
drawGrid() | Draws the four range rings, their labels and the angle lines |
drawBlips(now) | Draws the red dots and fades them out over 5 seconds |
drawSweep(t) | Draws the bright green line and its fading trail |
render() | Redraws everything at your screen's refresh rate |
poll() | Fetches new readings from /data every 100 ms |
Each request to /data returns a small JSON message like this:
{"t":47209,"seq":120,"period":6000,"mid":90.0,"amp":75.0,"maxCm":100,"flip":false,"d":42.5,"r":[[88.4,42.5],[91.2,42.1]]}Here t is the ESP32's sweep clock, seq tells the browser which readings it already has, and d is the latest distance, or -1 if nothing is in range. r lists new readings as [angle, distance]. The other values describe the sweep, so the browser can draw it without any settings of its own.
Step 5: Upload and Find the IP Address
- Click Upload and wait for the "Hard resetting" message at the end. If it stops at "Connecting...", hold the BOOT button until writing starts.
- Open Tools → Serial Monitor at 115200 baud and press the EN (reset) button.
- The OLED shows
Connecting WiFi, thenOpen in browser:with the IP address for 5 seconds. The Serial Monitor prints the same address. - The servo starts sweeping after the network is ready, which can take up to 15 seconds. The D15 pin can make the servo twitch briefly at power-up, which is harmless.
Step 6: Open the Dashboard and Test It
- On a phone or laptop on the same Wi-Fi, open
http://followed by the IP address, such ashttp://192.168.1.50. Typehttp://in full, because some browsers tryhttps://first. - Check that the status under the radar says LIVE and the green line is moving.
- Hold a book flat, 20 to 30 cm in front of the sensor. Red blips should appear at that distance and angle, and the same object should appear as dots on the OLED.
- Move the book closer. The buzzer should beep faster.
- If an object on your left shows up on the right of the screen, set
FLIP_DISPLAYtotrueand upload again.
Settings You Can Change
All of these are near the top of the sketch:
| Setting | Default | What it does |
|---|---|---|
SWEEP_ONE_WAY_MS | 3000 | Time for one sweep. Higher is slower and smoother |
SWEEP_MIN, SWEEP_MAX | 15, 165 | The sweep's limits in degrees |
MAX_CM | 100 | The radar's outer ring. Farther objects are ignored |
BUZZER_ALERT_CM | 50 | Buzzer range. Set to 0 for silence |
FLIP_DISPLAY | false | Mirrors the dashboard and OLED |
USE_OLED | 1 | Set to 0 if you aren't using a display |
The HC-SR04 sees in a cone roughly 15° wide, so objects look wider on the radar than they really are. Flat, hard surfaces reflect best. Soft or angled objects may not show at all.
Common Problems and How to Actually Fix Them
No blips, and distance always shows --. Check that VCC is on VIN with 5V, not 3V3, and that TRIG is on D5. Then check the divider order: 1 kΩ from ECHO to D18, and 2 kΩ from D18 to GND. Test with a flat object within 1 m.
Servo moves in jerks. Check power first: use a separate 5V supply, share GND with the ESP32, and add a 470 µF capacitor across the servo's 5V and GND. Then check that the sensor is balanced and its wires are slack. Raising SWEEP_ONE_WAY_MS to 4000 also smooths the motion.
Servo buzzes at the ends of the sweep. It's probably pressing against its mechanical limit. Narrow the sweep, for example to SWEEP_MIN = 20 and SWEEP_MAX = 160.
The board resets randomly. If the Serial Monitor shows a brownout message, the supply is dipping. Give the servo its own 5V supply and try a different USB cable and port.
The IP appears, but the page won't open. Your phone or laptop must be on the same network, and guest networks often block devices from reaching each other. Use http://, not https://. Also turn off any VPN on that device.
The same blip appears at the same angle on every sweep. The sensor is probably detecting its own wires or bracket, or something next to it on the bench. Move it clear of the sensor's path.
The buzzer beeps all the time. Something is inside BUZZER_ALERT_CM, often a nearby keyboard or wall. Lower the value or clear the area.
OLED is blank. Read the labels on the module, because VCC and GND are often swapped. If the screen shows noise, your module may use an SSD1306 chip rather than an SH1106.
Upload fails with "Failed to connect to ESP32". Hold BOOT when the upload starts, and use a USB cable that carries data. If it still fails, unplug the servo signal wire from D15 during upload.
You moved tasks to other cores and things froze. Keep the sensor, web server and OLED on core 0. The servo task keeps core 1 busy, and anything else placed there can stop running. Wi-Fi must also start before the tasks do.
A Word on Security
The dashboard has no login, so anyone on the same network can view it. That's fine for a home network or a demo, but don't expose it to the internet. Change the AP_PASS backup password before you deploy it anywhere, keeping it at least 8 characters.
What to Build Next
- Better range accuracy: swap the HC-SR04 for a VL53L1X time-of-flight sensor, which has a much narrower beam.
- Intruder alarm: send a phone notification through Telegram or MQTT when something enters a chosen zone.
- 3D scanning: add a tilt servo and build up a rough point cloud.
- Data logging: save each angle and distance to a microSD card or a server.
- Temperature correction: use a DS18B20 to correct the speed of sound for more accurate distances.
Terms Used in This Guide
| Term | Simple meaning |
|---|---|
| Sketch | The name Arduino IDE uses for a program |
| GPIO / D pin | A numbered pin on the ESP32 that the code can control or read |
| GND | Ground, the shared negative side of the circuit |
| VIN | The ESP32's 5V pin while it's powered by USB |
| I2C | A two-wire connection, used here by the OLED on SDA and SCL |
| IP address | The number you type in a browser to reach the ESP32 |
| Station mode | The ESP32 joins your Wi-Fi router |
| Access Point mode | The ESP32 creates its own Wi-Fi network |
| Voltage divider | Two resistors that lower a voltage to a safe level |
| Blip | A red dot on the radar showing a detected object |
Frequently Asked Questions
Can I build this without the OLED or buzzer? Yes. Set USE_OLED to 0 to skip the display, and set BUZZER_ALERT_CM to 0 or leave the buzzer unconnected.
Can I use an SSD1306 0.96-inch OLED? Yes, but you'll need to change the display library and driver in the code, because this version uses the SH1106 found on most 1.3-inch modules.
Will this work on an ESP8266? Not as written. It relies on the ESP32's two cores, FreeRTOS tasks and ESP32-specific libraries.
Do I really need the voltage divider? Yes. A direct connection may work for a while, but it runs the pin above its rated voltage and can damage the ESP32.
What's the maximum range? The HC-SR04 is rated to about 4 m, but this radar is set to 100 cm, which suits a desk or small room and keeps readings dependable. You can raise MAX_CM.
Can several people watch at once? Yes. Each browser keeps its own place in the readings, though the ESP32 is a small server, so keep it to a few viewers.
Where can I get the code? It's in the full listing above and in the SolderHub projects repository on GitHub.


