Build an ultrasonic radar with a live web display on the Raspberry Pi

Mount the ultrasonic sensor on a servo and turn the Raspberry Pi into a radar. A background thread sweeps from side to side and measures every 3 degrees, and a web page on your phone draws a glowing radar screen...
  • Level:Advanced
  • Duration: 1 h 30 min
  • Ages 12+
  • Platform: Raspberry Pi

What you'll need

Build an ultrasonic radar with a live web display on the Raspberry Pi – EEMENTOR STEM™ lesson

Ships and airports find things they can't see with radar: a beam sweeps round and round, and every echo becomes a dot on a screen. In this project you build the same thing with sound. The ultrasonic sensor sits on a servo that sweeps from left to right and back, the Raspberry Pi measures the distance every 3 degrees, and a web page on your phone draws a glowing green radar screen that updates live. Walk your hand in front of it and watch the dots appear.

What you'll learn

  • How to combine a servo and an ultrasonic sensor into a scanner
  • How a background thread keeps sweeping while Flask serves web pages
  • How server-sent events push data to the browser the moment it is measured
  • How to draw a radar screen on an HTML canvas with a little JavaScript
  • Why a servo can jitter on the Pi, and how the pigpio pin factory fixes it

What you need

  • Raspberry Pi 4 Model B with Raspberry Pi OS and its USB-C power supply (use the official 5 V 3 A supply, the servo needs it), connected to your Wi-Fi
  • Ultrasonic sensor HC-SR04 (ESP32 IoT Starter Kit)
  • Servo motor with its horns and screws (ESP32 IoT Starter Kit)
  • 3 resistors of 10 kΩ and 1 capacitor of 100 µF (ESP32 IoT Starter Kit)
  • Breadboard and jumper wires, including female-to-male wires (ESP32 IoT Starter Kit)
  • Double-sided tape, a rubber band or a hot glue gun, to fix the sensor to the servo horn

Measured distance with the HC-SR04 before? Measure distance with an ultrasonic sensor on the Raspberry Pi explains the sensor and the voltage divider in detail. This project uses the same pins. If Flask isn't installed yet, run sudo apt install python3-flask.

Look after your Pi: the HC-SR04 runs on 5 V and its Echo pin sends 5 V pulses, which would damage a GPIO pin. The three 10 kΩ resistors form a voltage divider that turns them into about 3.3 V. Build the divider before you connect Echo, and shut the Pi down before you change the wiring.

Build the scanner

  1. Push the round or cross-shaped horn onto the servo. Turn it gently by hand to one end, then put the horn back on pointing straight along the servo, so the full 180° sweep goes from left to right.
  2. Fix the HC-SR04 to the horn with double-sided tape or a drop of hot glue, with its two "eyes" facing forward and its pins pointing down or back.
  3. Use four female-to-male wires from the sensor pins to the breadboard, long enough to let the sensor turn without pulling.
  4. Stand the servo on the table, or tape it to a box, so the sensor sweeps over an open space.

Wiring

Breadboard wiring diagram: HC-SR04 VCC to the plus rail, Trig to GPIO 23 (pin 16), Echo through a 10 kilohm resistor to GPIO 24 (pin 18) with two more 10 kilohm resistors to the minus rail; servo GND, plus and signal to the minus rail, plus rail and GPIO 18 (pin 12); 100 microfarad capacitor across the rails; plus rail to 5V (pin 2), minus rail to GND (pin 9) on a Raspberry Pi 4.
Breadboard view. Check each connection against the wiring table below.
From To
HC-SR04 VCC The red (+) rail
HC-SR04 Trig GPIO 23 (pin 16)
HC-SR04 Echo 10 kΩ resistor (R1) → the divider point
The divider point GPIO 24 (pin 18), and 10 kΩ (R2) → 10 kΩ (R3) → the blue (−) rail
HC-SR04 GND The blue (−) rail
Servo brown (GND) The blue (−) rail
Servo red (+) The red (+) rail
Servo orange (signal) GPIO 18 (pin 12)
100 µF capacitor Long leg (+) to the red (+) rail, short leg (−, striped side) to the blue (−) rail
The red (+) rail 5V (pin 2)
The blue (−) rail GND (pin 9)

The capacitor is a small energy store right next to the servo. Each time the servo starts moving it draws a burst of current, and the capacitor helps cover it, so the 5 V supply stays steady for the sensor and the Pi.

The program

Save the program as radar.py in your home folder and run it in Thonny. The servo moves to 0° and starts sweeping, and the Shell prints a line whenever something is closer than 30 cm. On your phone or computer, open http://<your-pi>.local:5000, for example http://raspberrypi.local:5000, or use the IP address that hostname -I shows.

# Ultrasonic radar: a servo sweeps the HC-SR04, and a web page draws what it sees, live
from gpiozero import DistanceSensor, AngularServo
from flask import Flask, Response
from queue import Queue, Empty
import json, threading, time

sensor = DistanceSensor(echo=24, trigger=23, max_distance=2, queue_len=2, partial=True)
servo = AngularServo(18, min_angle=0, max_angle=180,
                     min_pulse_width=0.0005, max_pulse_width=0.0024)
STEP = 3                 # degrees between measurements
SETTLE = 0.12            # seconds for the servo to move and the sensor to measure
clients = []             # one queue per open web page
clients_lock = threading.Lock()
running = True

def publish(event):
    with clients_lock:
        for q in clients:
            q.put(event)

def measure(angle):
    servo.angle = angle
    time.sleep(SETTLE)                     # wait for fresh echoes at the new angle
    cm = round(sensor.distance * 100, 1)   # 200 cm means "nothing in range"
    publish({"angle": angle, "cm": cm})
    return cm

def sweep():
    angles = list(range(0, 181, STEP))
    while running:
        for a in angles + angles[::-1][1:-1]:   # 0 → 180, then back towards 0
            if not running:
                break
            cm = measure(a)
            if cm < 30:
                print(f"Object at {a:3d}°, {cm:5.1f} cm")
    servo.detach()                          # stop the pulses so the servo rests quietly

app = Flask(__name__)

@app.route("/")
def page():
    return PAGE

@app.route("/stream")
def stream():
    def events():
        q = Queue()
        with clients_lock:
            clients.append(q)
        try:
            while True:
                try:
                    yield "data: " + json.dumps(q.get(timeout=15)) + "\n\n"
                except Empty:
                    yield ": still here\n\n"        # keeps the connection open
        finally:
            with clients_lock:
                clients.remove(q)
    return Response(events(), mimetype="text/event-stream",
                    headers={"Cache-Control": "no-cache"})

PAGE = """<!doctype html><meta name=viewport content="width=device-width,initial-scale=1">
<title>Ultrasonic radar</title>
<style>body{margin:0;background:#04120A;color:#7CFC9A;font-family:monospace;text-align:center}
canvas{width:100%;max-width:800px}</style>
<h2>Ultrasonic radar</h2><canvas id=c width=800 height=440></canvas><p id=info>waiting…</p>
<script>
const c = document.getElementById("c"), g = c.getContext("2d");
const R = 380, X = 400, Y = 420, MAX = 200;        // radius in px, centre, max range in cm
const dist = new Array(181).fill(MAX);
function xy(angle, cm) { const a = Math.PI * (1 - angle / 180), r = R * Math.min(cm, MAX) / MAX;
  return [X + r * Math.cos(a), Y - r * Math.sin(a)]; }
function draw(sweep) {
  g.fillStyle = "rgba(4,18,10,0.25)"; g.fillRect(0, 0, c.width, c.height);   // fade old frames
  g.strokeStyle = "#1E6B3A"; g.lineWidth = 1;
  for (const cm of [50, 100, 150, 200]) { g.beginPath(); g.arc(X, Y, R * cm / MAX, Math.PI, 0); g.stroke();
    g.fillStyle = "#3FA864"; g.fillText(cm + " cm", X - R * cm / MAX + 4, Y - 4); }
  for (let a = 0; a <= 180; a += 30) { const [x, y] = xy(a, MAX); g.beginPath(); g.moveTo(X, Y); g.lineTo(x, y); g.stroke(); }
  const [sx, sy] = xy(sweep, MAX); g.strokeStyle = "#7CFC9A"; g.lineWidth = 3;
  g.beginPath(); g.moveTo(X, Y); g.lineTo(sx, sy); g.stroke();
  for (let a = 0; a <= 180; a++) if (dist[a] < MAX) { const [x, y] = xy(a, dist[a]);
    g.fillStyle = dist[a] < 30 ? "#FF5A5A" : "#7CFC9A"; g.fillRect(x - 3, y - 3, 6, 6); }
}
const es = new EventSource("/stream");
es.onmessage = (e) => { const d = JSON.parse(e.data);
  for (let a = d.angle - 1; a <= d.angle + 1; a++) if (a >= 0 && a <= 180) dist[a] = d.cm;
  info.textContent = `${d.angle}°  ${d.cm >= MAX ? "nothing in range" : d.cm + " cm"}`; draw(d.angle); };
es.onerror = () => { info.textContent = "connection lost, retrying…"; };
</script>"""

if __name__ == "__main__":
    threading.Thread(target=sweep, daemon=True).start()
    try:
        app.run(host="0.0.0.0", port=5000, threaded=True)
    finally:
        running = False

A steadier servo with pigpio

On Raspberry Pi OS, gpiozero uses the lgpio library by default, which makes the servo pulses in software. When Linux is busy, a pulse can come a little late, and the servo twitches. The pigpio library times the pulses with the Pi's hardware instead, which works on the Raspberry Pi 4 and earlier models. To try it, run in a terminal:

sudo apt install pigpio python3-pigpio
sudo systemctl enable --now pigpiod
GPIOZERO_PIN_FACTORY=pigpio python3 radar.py

The program stays exactly the same: the environment variable just tells gpiozero which library to use. If the servo still twitches, check the power first, because a weak supply causes most servo jitter.

What you should see

The page shows a half circle with rings at 50, 100, 150 and 200 cm. A bright green line follows the servo, and every measurement leaves a dot that slowly fades: green for objects, red for anything closer than 30 cm. Hold a book about 40 cm in front of the sensor and you see a short arc of dots at that distance and angle. Move it, and on the next sweep the dots follow. A full sweep there and back takes about 15 seconds. Open the page on two phones and both update together.

The radar web page on a tablet: a green half-circle radar with rings at 50 to 200 cm, the sweep line at 63 degrees, dots for a cupboard at about 1.4 m, a book at about 70 cm and a hand in red under 30 cm, next to the Thonny Shell printing objects closer than 30 cm.
Every echo becomes a dot. Red dots are closer than 30 cm.

How it works

How it works: the sweep thread calls measure at each angle, measure moves the servo, waits 0.12 seconds and publishes the angle and distance to one queue per open page, and the browser receives them as server-sent events and draws dots on a canvas; example data lines from the stream.
A thread measures, one queue per page fans the readings out, and the browser draws them.

Two jobs at once. Flask spends its time waiting for browsers, and the radar must keep sweeping whatever the browsers do. So the program starts sweep() in its own thread. It runs through the angles 0, 3, 6 … 180 and back again. At each angle, measure() moves the servo, waits 0.12 s for it to arrive and for the sensor to take fresh readings, then reads the distance in centimetres.

Fresh readings. gpiozero's DistanceSensor measures all the time in the background and averages the last few results. With queue_len=2 it only averages two, so a reading taken after the 0.12 s wait belongs to the new angle and not to the old one. max_distance=2 means anything beyond 2 m, or no echo at all, reads as 200 cm, "nothing in range".

Server-sent events. Normally a browser asks and the server answers once. With server-sent events (SSE) the browser opens /stream and keeps the connection open, and the server writes a new line, such as data: {"angle": 63, "cm": 41.5}, every time it has news. Each open page gets its own Queue, and publish() puts every measurement into all of them. If nothing happens for 15 seconds, the stream sends a comment line so the connection doesn't time out. In the browser, EventSource receives the lines and even reconnects by itself if the Pi restarts.

Drawing the radar. The page turns each angle and distance into an x and y position with a little trigonometry: 0° is on the left, 180° on the right, and 200 cm is the edge of the screen. Before every new frame it paints a see-through dark rectangle over the old one, which makes old dots fade slowly, just like on a real radar screen.

Try this next

  • Make the sweep faster with STEP = 5 and SETTLE = 0.08, or more detailed with STEP = 1. What is the best balance?
  • Sound an alarm: add a buzzer and beep when something is closer than 30 cm.
  • Start the radar at boot with a systemd service, as in the smart relay panel.
  • Keep going with the next project: Build a keypad alarm with an LCD and phone alerts.

Troubleshooting

  • Every reading is 200 cm: check the divider and that Echo goes through R1 to GPIO 24. Swapped Trig and Echo wires also give no echo.
  • The servo twitches or the Pi restarts: use the official power supply, check the capacitor's direction, and try the pigpio pin factory above.
  • The servo hums at the ends or doesn't reach 180°: servos differ. Try max_pulse_width=0.0023 and min_pulse_width=0.0006.
  • The page shows "waiting…" forever: check that radar.py is still running. Some browser extensions block event streams, so try another browser.
  • The dots appear at the wrong side: your servo turns the other way. Mirror the page by changing 1 - angle / 180 to angle / 180 in the xy() function.
  • Soft things are missing: curtains, cushions and clothes absorb sound, and objects at a steep angle bounce the echo away. Hard, flat surfaces facing the sensor work best.