What You Will Build
A car's parking sensor does one simple job: it tells you how close the obstacle is, and it does so with sound. The closer you get, the faster the beeping, until it becomes a continuous tone. In this project you will build a working miniature version with an Arduino Uno, an HC-SR04 ultrasonic sensor, a 16x2 I2C LCD and a buzzer.
When it is finished it will:
- Measure distance from about 2 cm to 400 cm using ultrasound
- Show the distance on the LCD, refreshed five times a second
- Stay silent when nothing is within 100 cm, beep slowly as an object enters that zone, and beep faster as it approaches
- Switch to a continuous tone and a "TOO CLOSE!" message inside 20 cm
Along the way you will learn how an ultrasonic sensor turns time into distance, why the speed of sound depends on temperature, how to smooth out noisy readings with a median filter, and how to run a sensor, a display and a buzzer at the same time with millis() instead of delay(). The same techniques carry directly into obstacle-avoiding robots, smart dustbins, tank level monitors and distance alarms.
Components
7 itemsNeed these parts? Get this build sheet by email
Parts list with buy links, plus new builds as they're published. By subscribing you agree to our Privacy Policy. Unsubscribe anytime.
⚠️ Warning
Use an active buzzer, not a passive one. An active buzzer has its own oscillator and sounds when you simply apply 5 V. A passive buzzer is a bare piezo disc that needs a changing signal from tone(), so driving it with digitalWrite(HIGH) produces only a faint click. Active buzzers also have polarity: the longer leg or the leg marked + goes to the signal side.
How the HC-SR04 Measures Distance
The HC-SR04 works like a tiny bat. It sends out a short burst of 40 kHz ultrasound, far above what humans can hear, and then listens for the echo. The time between sending and receiving tells you how far away the object is.
The Four Pins
| Pin | Name | Purpose |
|---|---|---|
| VCC | Power | 5 V supply (it draws about 15 mA) |
| Trig | Trigger | A 10 µs HIGH pulse starts one measurement |
| Echo | Echo | Goes HIGH when the burst is sent and stays HIGH until the echo returns |
| GND | Ground | Common ground |
On a trigger pulse the module sends eight cycles of 40 kHz sound, then raises the Echo pin and holds it HIGH for exactly as long as the sound took to travel out and back. Your job is to measure that pulse width, which pulseIn() does in microseconds.
Turning Time Into Distance
Sound travels at roughly 343 m/s in air at 20 °C, which is 0.0343 cm per microsecond. The measured pulse covers the journey to the object and back, so you divide by two:
distance_cm = (duration_us × speed_cm_per_us) / 2For example, an echo pulse of 1,166 µs gives 1,166 × 0.0343 ÷ 2 ≈ 20 cm.
Why Temperature Matters
The speed of sound is not constant. It rises by about 0.6 m/s for every degree Celsius, following v = 331.3 + 0.606 × T m/s. At 0 °C that is about 331 m/s and at 30 °C it is about 349.5 m/s. If you assume 343 m/s on a cold morning, a reading near 4 m can be out by roughly 14 cm. Our code takes the ambient temperature as a setting and calculates the speed for you, and you can later feed it from a temperature sensor such as a DHT22 for automatic correction.
Key Specifications
| Parameter | Typical value |
|---|---|
| Operating voltage | 5 V DC |
| Measuring range | 2 cm to 400 cm |
| Resolution | about 0.3 cm |
| Measuring angle | about 15° cone |
| Trigger signal | 10 µs TTL pulse |
| Minimum cycle time | about 60 ms between measurements |
What Ultrasound Cannot Do Well
Soft materials such as cloth, foam and thick curtains absorb sound and return weak echoes. Hard surfaces set at a steep angle, roughly beyond 45° to the sensor, deflect the sound away instead of back. Very small or thin objects, like a pole, may not be seen at all. And the module is not waterproof. For a real outdoor installation look at a sealed probe such as the JSN-SR04T, which trades a larger minimum distance, around 20 to 25 cm, for weather resistance.
Try the Sensor in the Simulator
Before wiring anything, you can run the HC-SR04 in the SolderHub Simulator below. This circuit is the sensor on its own: Trig is on pin 9 as in this project, but Echo is on pin 10 rather than pin 8, and the distance goes to the Serial Monitor instead of the LCD. Change the simulated distance and watch the echo time and the printed reading follow it, then come back and build the full alarm.
Try it in the simulator
Wiring
The LCD and the sensor both run from the Uno's 5 V rail. The I2C LCD needs only two signal wires, which leaves plenty of pins free.
| Arduino Uno | HC-SR04 | I2C LCD | Buzzer |
|---|---|---|---|
| 5V | VCC | VCC | see below |
| GND | GND | GND | GND |
| A4 (SDA) | none | SDA | none |
| A5 (SCL) | none | SCL | none |
| Pin 9 | Trig | none | none |
| Pin 8 | Echo | none | none |
| Pin 11 | none | none | + (signal) |
Driving the Buzzer Properly
A small active buzzer often draws 25 to 30 mA, which is above the 20 mA recommended per Uno pin. A single buzzer on pin 11 usually works fine, but it is a poor habit. For a robust build use an NPN transistor: connect the buzzer's + to 5 V, its − to the transistor's collector, the emitter to GND, and pin 11 to the base through a 1 kΩ resistor. The code is identical either way, because HIGH on pin 11 still means "buzzer on".
Powering the I2C LCD
The I2C backpack is a small PCF8574 chip soldered to the back of the display. It converts the display's many parallel pins into two I2C lines. The LCD needs 5 V, not 3.3 V, or the text will be faint or invisible. A small blue trimmer on the backpack sets the contrast.
Find Your LCD's I2C Address
I2C devices answer to an address, and LCD backpacks ship with one of two common values: 0x27 (PCF8574T) or 0x3F (PCF8574AT). If you use the wrong one the backlight comes on but no text appears, so it is worth checking before you run the main sketch.
Install the library first: open Sketch → Include Library → Manage Libraries, search for LiquidCrystal I2C by Frank de Brabander, and install it. Then upload this scanner and open the Serial Monitor at 9600 baud:
// I2C scanner - prints the address of every device it finds
#include <Wire.h>
void setup() {
Wire.begin();
Serial.begin(9600);
Serial.println("Scanning I2C bus...");
byte found = 0;
for (byte address = 1; address < 127; address++) {
Wire.beginTransmission(address);
if (Wire.endTransmission() == 0) {
Serial.print("Device found at 0x");
if (address < 16) Serial.print("0");
Serial.println(address, HEX);
found++;
}
}
if (found == 0) Serial.println("No I2C devices found - check SDA/SCL wiring");
else Serial.println("Scan complete");
}
void loop() {}How the Code Is Designed
A beginner version of this project does everything in order: ping, calculate, print, beep, delay(). It works, but the buzzer timing wobbles because the loop is blocked while the sensor waits and the LCD updates. We avoid that by splitting the work into three independent jobs, each controlled by its own millis() timer:
- Measure every 60 ms, which respects the sensor's minimum cycle time. Each reading goes into a three-value history and the median is used, so one stray echo cannot cause a wrong alarm.
- Buzzer logic runs on every pass through
loop(). It decides, from the current distance, whether to stay silent, beep at a distance-dependent rate, or hold a continuous tone. Beeps are timed withmillis(), never withdelay(). - Display refreshes every 200 ms. Updating the LCD more often wastes time and can make the text flicker.
The beep rate is calculated by linear interpolation between two distances. At 100 cm (ALERT_CM) the gap between beeps is 700 ms. At 20 cm (DANGER_CM) it shrinks to 60 ms, and inside 20 cm the tone is continuous. That gives a smooth, natural ramp, much closer to a real parking sensor than a crude two-step alarm.
/*
HC-SR04 parking alert with I2C LCD and buzzer
- Median-of-3 filtering for stable readings
- Temperature-corrected speed of sound
- Fully non-blocking: measurement, buzzer and LCD each run on millis()
*/
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // use 0x3F if the scanner reports it
// ---------- Pins ----------
const uint8_t TRIG_PIN = 9;
const uint8_t ECHO_PIN = 8;
const uint8_t BUZZER_PIN = 11;
// ---------- Tuning ----------
const float TEMP_C = 25.0; // ambient temperature in degrees C
const float MAX_CM = 400.0; // sensor limit
const float ALERT_CM = 100.0; // beeping starts inside this distance
const float DANGER_CM = 20.0; // continuous tone inside this distance
const unsigned long MEASURE_MS = 60; // min cycle time of the HC-SR04
const unsigned long LCD_MS = 200; // LCD refresh interval
const unsigned long BEEP_ON_MS = 40; // length of each beep
const unsigned long BEEP_GAP_MIN_MS = 60; // gap between beeps at DANGER_CM
const unsigned long BEEP_GAP_MAX_MS = 700; // gap between beeps at ALERT_CM
// ---------- State ----------
float soundCmPerUs; // calculated in setup()
float history[3] = {MAX_CM, MAX_CM, MAX_CM};
uint8_t historyIndex = 0;
float distanceCm = MAX_CM;
unsigned long lastMeasure = 0;
unsigned long lastLcd = 0;
unsigned long lastBeepChange = 0;
bool buzzerOn = false;
// ---------- Helpers ----------
float readDistanceCm() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
unsigned long duration = pulseIn(ECHO_PIN, HIGH, 30000UL); // 30 ms timeout
if (duration == 0) return MAX_CM; // no echo
float cm = duration * soundCmPerUs / 2.0;
return (cm > MAX_CM) ? MAX_CM : cm;
}
float median3(float a, float b, float c) {
if ((a >= b && a <= c) || (a <= b && a >= c)) return a;
if ((b >= a && b <= c) || (b <= a && b >= c)) return b;
return c;
}
void updateBuzzer(unsigned long now) {
if (distanceCm >= ALERT_CM) { // far away: silent
digitalWrite(BUZZER_PIN, LOW);
buzzerOn = false;
return;
}
if (distanceCm <= DANGER_CM) { // very close: continuous tone
digitalWrite(BUZZER_PIN, HIGH);
buzzerOn = true;
return;
}
// In between: beep gap shrinks as the object gets closer
float t = (distanceCm - DANGER_CM) / (ALERT_CM - DANGER_CM); // 0..1
unsigned long gap = BEEP_GAP_MIN_MS +
(unsigned long)(t * (BEEP_GAP_MAX_MS - BEEP_GAP_MIN_MS));
if (buzzerOn) {
if (now - lastBeepChange >= BEEP_ON_MS) {
digitalWrite(BUZZER_PIN, LOW);
buzzerOn = false;
lastBeepChange = now;
}
} else if (now - lastBeepChange >= gap) {
digitalWrite(BUZZER_PIN, HIGH);
buzzerOn = true;
lastBeepChange = now;
}
}
void updateLcd() {
lcd.setCursor(0, 0);
if (distanceCm >= MAX_CM) {
lcd.print("Dist: --- cm ");
} else {
lcd.print("Dist: ");
lcd.print(distanceCm, 1);
lcd.print(" cm ");
}
lcd.setCursor(0, 1);
if (distanceCm <= DANGER_CM) lcd.print(">> TOO CLOSE! <<");
else if (distanceCm < ALERT_CM) lcd.print("Caution ");
else lcd.print("Clear ");
}
// ---------- Arduino entry points ----------
void setup() {
Serial.begin(9600);
// Speed of sound in cm per microsecond: v(m/s) = 331.3 + 0.606 * T
soundCmPerUs = (331.3 + 0.606 * TEMP_C) / 10000.0;
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(BUZZER_PIN, OUTPUT);
digitalWrite(BUZZER_PIN, LOW);
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Parking Alert");
lcd.setCursor(0, 1);
lcd.print("Starting...");
delay(1500);
lcd.clear();
Serial.println("HC-SR04 parking alert ready");
}
void loop() {
unsigned long now = millis();
// Job 1: measure and filter
if (now - lastMeasure >= MEASURE_MS) {
lastMeasure = now;
history[historyIndex] = readDistanceCm();
historyIndex = (historyIndex + 1) % 3;
distanceCm = median3(history[0], history[1], history[2]);
Serial.println(distanceCm); // open Tools > Serial Plotter to graph it
}
// Job 2: buzzer
updateBuzzer(now);
// Job 3: display
if (now - lastLcd >= LCD_MS) {
lastLcd = now;
updateLcd();
}
}Key Parts of the Code Explained
| Section | Purpose |
|---|---|
soundCmPerUs = (331.3 + 0.606 * TEMP_C) / 10000.0 | Converts the temperature-based speed of sound from m/s to cm per microsecond |
pulseIn(ECHO_PIN, HIGH, 30000UL) | Measures the echo pulse width, giving up after 30 ms (about 5 m) so a missing echo cannot freeze the program |
median3() | Returns the middle of the last three readings, ignoring a single wild value |
t = (distanceCm - DANGER_CM) / (ALERT_CM - DANGER_CM) | Converts distance into a 0 to 1 position inside the alert zone |
gap = BEEP_GAP_MIN_MS + t * (range) | Linear interpolation from fast beeps to slow beeps |
now - lastMeasure >= MEASURE_MS | Non-blocking timer that also stays correct when millis() wraps around |
One detail worth noticing: pulseIn() still blocks while it waits for the echo, up to 30 ms. That is short enough not to disturb the beeps, but it is why the display and buzzer logic avoid long delay() calls anywhere else.
Upload and Test
- Connect the Uno by USB and select Tools → Board → Arduino Uno and the correct port.
- Make sure
LiquidCrystal_I2Cis installed and the address in the sketch matches your scanner result. - Click Upload. After a short start-up message, the LCD should show a distance.
- Open the Serial Monitor at 9600 baud, or better, Tools → Serial Plotter, to watch the distance as a live graph while you move your hand.
What You Should See
| Object distance | LCD line 1 | LCD line 2 | Buzzer |
|---|---|---|---|
| No object / out of range | Dist: --- cm | Clear | Silent |
| Above 100 cm | Dist: 130.0 cm | Clear | Silent |
| About 100 cm | Dist: 98.0 cm | Caution | One short beep roughly every 0.7 s |
| About 60 cm | Dist: 60.0 cm | Caution | About 2 beeps per second |
| About 30 cm | Dist: 30.0 cm | Caution | About 5 beeps per second |
| 20 cm or less | Dist: 12.0 cm | >> TOO CLOSE! << | Continuous tone |
Calibrate Against a Ruler
Never trust a distance sensor until you have checked it. Place a flat book at 10 cm, 30 cm and 100 cm from the sensor using a tape measure, and compare the LCD. A small constant error is normal. If readings are consistently too high or low by a few percent, adjust TEMP_C to the real room temperature first, because that is the most common cause.
Troubleshooting
| Problem | Most likely cause | Fix |
|---|---|---|
| Backlight is on but no text | Wrong I2C address | Run the scanner and set the address it reports, usually 0x27 or 0x3F |
| Solid white blocks on the LCD | Contrast set too high | Turn the small blue trimmer on the backpack slowly |
| LCD faint or blank | Powered from 3.3 V | Power the LCD from the 5 V pin |
Distance stuck at --- | Echo not received | Check Trig on pin 9, Echo on pin 8, 5 V and GND, and that the sensor faces the object |
| Readings jump around | Soft or angled target, or a wobbly mount | Use a flat hard target and fix the sensor in place. The median filter helps but cannot fix a bad echo |
| Buzzer only clicks | Passive buzzer fitted | Replace it with an active buzzer, or switch to tone() |
| Buzzer sounds weak or the Uno resets | Too much current from the pin | Drive the buzzer through an NPN transistor |
| Readings drift with room temperature | TEMP_C set wrongly | Update the setting, or add a temperature sensor |
| Reading is always about 2 to 3 cm | Echo being picked up from your own breadboard or wires | Aim the sensor clear of nearby objects |
Extensions: Make It Your Own
Once your parking alert is stable, here are some upgrades that each teach something new:
- LED bar graph: add three to five LEDs, each with its own 220 Ω resistor, and light more of them as the object approaches.
- Pitch instead of rate: use a passive buzzer with
tone(pin, frequency)and raise the pitch as the distance shrinks. - Mute button: add a push button on
INPUT_PULLUPto silence the buzzer without stopping the display. - Automatic temperature correction: read a DHT22 or an LM35 and feed the value into the speed-of-sound formula.
- Radar sweep: mount the sensor on an SG90 servo and scan an arc to detect objects over a wider area.
- Wireless version: port the project to an ESP32 and publish the distance over Wi-Fi or MQTT. The 5 V Echo output needs a voltage divider before it reaches a 3.3 V pin.
What You Learned
You built a complete distance-alert system and, more importantly, the habits behind it: calculating from physics instead of guessing constants, filtering sensor noise, timing several jobs with millis(), checking a sensor against a ruler, and choosing an output device that matches how it is driven. These patterns apply to nearly every sensor project you will build next.
For a related build that measures liquid levels with the same sensor, see the Water Level Monitor, and for the Uno's power pins and current limits when you add more parts, see the Arduino Uno pinout guide. The HC-SR04 guide covers the sensor itself in more depth.



