Skip to main content
emobility.academy
B.Tech / BERadar & lidarBeginner About 4 weeksADAS & AUTOSAR

Ultrasonic Parking Sensor System with Distance Zones and Alerts

Build a reverse parking aid on the DIYguru EV Embedded Development Kit with an HC-SR04 add-on: timed echo measurement on the STM32, filtered distance, zones on the LCD and RGB LEDs, a buzzer that beeps faster as obstacles near, and distance and zone sent on CAN.

Tools: Microcontroller · Embedded C

Ultrasonic Parking Sensor System with Distance Zones and Alerts: Students studying an electric car with DIYguru trainers in the workshop
Representative photo from DIYguru's EV lab, not of this specific project.

The problem

Parking sensors are one of the most common driver assistance features, and they show the full chain from sensor timing to filtered measurement to clear driver warning. Ultrasonic sensors are cheap but give noisy readings, miss angled or soft surfaces and change with temperature, so a robust parking aid needs filtering, plausibility checks and careful zone design.

Objectives

  • Measure echo time with a timer input capture and convert to distance with temperature compensation.
  • Filter readings and reject outliers.
  • Define distance zones with hysteresis and drive LCD, LEDs and buzzer.
  • Publish distance and zone on CAN.
  • Measure accuracy, update rate and detection limits on a bench.

What you need

Tools and toolboxes

  • STM32CubeIDE — Project setup, timer and CAN configuration, build and debugging.
  • Embedded C with STM32 HAL — Firmware for input capture, filtering, display, buzzer and CAN.
  • Python — Logging UART data and computing accuracy statistics.
  • Wireshark — Optional decoding of CAN frames captured through a USB-CAN adapter with SocketCAN.

From the EV Embedded Development Kit

  • STM32F103C8T6 microcontroller unit (Arm Cortex-M3)
  • 16×2 LCD with contrast control
  • RGB LEDs and a buzzer
  • BMP280 pressure and temperature sensor
  • CAN bus interface with screw terminal
  • Serial UART interface

Software

  • STM32CubeIDE
  • Embedded C with STM32 HAL
  • Python with pyserial, pandas and Matplotlib
  • python-can or SocketCAN tools for logging CAN

Extra parts and data

  • HC-SR04 ultrasonic distance sensor — The kit has no ultrasonic sensor; the HC-SR04 provides trigger and echo pins for time-of-flight measurement.
  • Voltage divider or level shifter for the echo pin — The HC-SR04 echo output is 5 V, while STM32 inputs should be protected unless the chosen pin is confirmed 5 V tolerant.
  • USB-CAN adapter — CAN needs a second node to acknowledge frames; the adapter acts as that node and lets a PC log the messages.

Key concepts

Time of flight
Distance equals the speed of sound times the echo time divided by two, since the pulse travels out and back.
Temperature compensation
The speed of sound in air is about 331 m/s plus roughly 0.6 m/s per degree Celsius, so using the measured temperature improves accuracy.
Input capture
A timer feature that records the counter value at a signal edge, giving precise pulse timing without busy-waiting in software.
Median filter
Taking the median of the last few readings removes single spikes from missed or false echoes better than a simple average.

Step-by-step guide

  1. 1

    Define requirements and zones

    Set requirements for a rear parking aid: measurement range 20 to 200 cm, accuracy within a few centimetres, an update every 60 to 100 ms and four zones, for example clear above 150 cm, caution 80 to 150 cm, warning 40 to 80 cm and stop below 40 cm. Define the output for each zone: LED colour, beep interval and LCD text, with a continuous tone in the stop zone. Add hysteresis of a few centimetres on each boundary.

    Checkpoint: A requirements table listing range, accuracy, update rate, zone limits, hysteresis and outputs.

  2. 2

    Wire the sensor safely

    Power the HC-SR04 from 5 V, connect trigger to a GPIO output and connect echo through a resistor divider (for example 1 kΩ and 2 kΩ) to a timer input-capture pin. Share ground with the kit. Enable the kit's DIP switches for the LCD, RGB LEDs, buzzer, I2C and CAN. Mount the sensor on a fixed bracket facing a clear test area, with a tape measure laid along the floor.

    Checkpoint: A scope or logic analyser trace (or a UART print of pulse width) showing echo pulses at 3.3 V.

  3. 3

    Measure echo time with input capture

    Configure a timer at 1 MHz so each tick is 1 µs and set its channel to capture both rising and falling edges. Send a 10 µs trigger pulse, record the rising and falling capture values in the interrupt and compute the pulse width, handling timer overflow. Add a timeout of about 30 ms for no echo and report that as out of range. Trigger at a fixed rate from a timer tick, leaving time for echoes to die out.

    Checkpoint: Pulse widths printed over UART that change smoothly as a board is moved in front of the sensor.

  4. 4

    Convert to distance with temperature compensation

    Read temperature from the BMP280 over I2C once per second and compute the speed of sound as 331.3 + 0.606 × T m/s. Convert pulse width to distance. Log distances at five tape-measured positions from 20 to 200 cm, 50 readings each, with and without compensation, and compute mean error and standard deviation in Python. Also check for a constant offset caused by the sensor's internal delay and correct it with a single calibration constant, so remaining errors reflect noise rather than bias.

    Checkpoint: An accuracy table for five distances showing the effect of temperature compensation.

  5. 5

    Filter and check plausibility

    Apply a median filter over the last five readings, then a light exponential smoothing. Reject readings that jump by more than a plausible amount between updates unless confirmed by the next reading, and count consecutive timeouts to declare no object. Log raw and filtered values while moving a target and while introducing disturbances, such as briefly waving a hand through the beam, to show spikes being rejected.

    Checkpoint: Plots of raw against filtered distance showing spikes removed without large lag.

  6. 6

    Drive zones, LCD, LEDs and buzzer

    Implement a zone state machine with hysteresis on the filtered distance. Show distance in centimetres and the zone name on the LCD, set the RGB LED colour by zone and drive the buzzer from a timer so the beep interval shortens as distance falls, becoming continuous in the stop zone. Keep the buzzer timing independent of the measurement loop so the beep rhythm stays even.

    Checkpoint: Zones change cleanly while moving a target, with no flicker at boundaries and steady beep timing.

  7. 7

    Publish on CAN

    Configure the CAN peripheral at 500 kbit/s and define a frame, for example ID 0x3A0, with distance in centimetres as a 16-bit value, zone as one byte, a status byte (valid, out of range, sensor fault) and a rolling counter. Send it every 100 ms. Connect the USB-CAN adapter with correct termination and log frames on the PC to check the timing and contents, decoding them with a small script.

    Checkpoint: Logged CAN frames at 100 ms intervals whose decoded distance matches the LCD.

  8. 8

    Test detection limits

    Measure how detection changes with target type and angle: a flat board square-on and at 30 and 45 degrees, a thin pole, a soft cushion and a person's legs. For each, record the maximum reliable detection distance and the miss rate. Also test a target below the sensor axis to show the vertical blind spot. These limits explain why vehicles use several sensors and why such systems are only an aid.

    Checkpoint: A table of detection range and miss rate by target type and angle.

  9. 9

    Measure timing and write the report

    Measure the update period and the delay from an object entering a zone to the buzzer change, using a GPIO toggle and a logic analyser or timestamps over UART. Write a report covering requirements, wiring, timing, calibration, filtering, zone logic, CAN message definition and test results. State the limitations: one sensor, bench conditions and no vehicle integration. Bench testing only; the aid supports and does not replace the driver's own checks.

    Checkpoint: Measured update rate and warning delay, and a report with all test tables.

Testing & validation

  • Distance accuracy at five reference distances with and without temperature compensation.
  • Spike rejection shown in raw against filtered logs.
  • Detection range and miss rate by target type and angle.
  • CAN frame timing and content checked on a PC log.
  • Update period and zone-change delay measured.

Expected results

A working ultrasonic parking aid on the kit with temperature-compensated, filtered distance, staged visual and audible warnings, a CAN output and measured accuracy and detection limits.

Take it further

  • Add a second sensor and show the nearest obstacle and its side.
  • Show a distance bar graph on the OLED display.
  • Receive reverse-gear status over CAN to enable the aid only when reversing.
  • Model the zone logic in Stateflow and generate code with Embedded Coder.

Viva and review questions

Why divide the echo time by two?

The pulse travels to the object and back, so the measured time covers twice the distance.

Why use input capture instead of polling the echo pin?

Input capture records edge times in hardware with microsecond precision, independent of what the CPU is doing, so timing jitter is much lower.

Why add hysteresis to the zones?

Without it, a distance hovering at a boundary would make the zone, LEDs and beeps flicker between states.

Why can an angled board go undetected?

Ultrasound reflects specularly from smooth surfaces; at a steep angle the echo is reflected away from the sensor and never returns.

Learn it at DIYguru

These DIYguru courses and programmes teach what this project needs.

Related EV projects

All 100 ADAS & AUTOSAR projects