ROBOREAR
← Back to all articles
Projects

This $5 Sensor Knows When You're Too Close (ESP32 Distance Alarm System)

Imagine this. You're working on your laptop. Someone walks too close to your desk. BEEP. RED LIGHT. WARNING. ESP32 Distance Alarm. They step back. Silence. Blue light. Peace.

ShahrearApril 16, 20268 min read
This $5 Sensor Knows When You're Too Close (ESP32 Distance Alarm System)

This video is hosted by YouTube. It loads only when you press play, and YouTube may then set cookies. Watch on YouTube

The "Back Off!" Moment

Imagine this.

You're working on your laptop. Someone walks too close to your desk.

BEEP. RED LIGHT. WARNING. ESP32 Distance Alarm.

They step back.

Silence. Blue light. Peace.

This isn't a scene from a spy movie. It's a $5 sensor, an ESP32, and two LEDs.

I built an ESP32 Distance Alarm that watches a zone and reacts when someone gets too close. No camera. No internet. Just ultrasonic sound waves and a few lines of code.

And you can build it in 20 minutes.

This video is hosted by YouTube. It loads only when you press play, and YouTube may then set cookies. Watch on YouTube

What Are We Building?

ESP32 Distance Alarm System?

ComponentWhat It Does
HC-SR04 Ultrasonic SensorShoots sound waves, measures how long they take to bounce back
ESP32The brain – calculates distance, decides what to do
Red LED"DANGER ZONE" – you're too close!
Blue LED"Safe Zone" – you're good
Buzzer (Optional)Makes noise when someone crosses the line

How it works:

  1. Sensor shoots an ultrasonic pulse (you can't hear it)

  2. Pulse hits an object and bounces back

  3. ESP32 measures the time

  4. Distance = (Time × Speed of Sound) / 2

  5. If distance < 30cm → Red LED + Buzzer

  6. If distance > 30cm → Blue LED + Peace

ESP32 distance alarm circuit diagram using HC-SR04 ultrasonic sensor, LEDs, and a buzzer on a breadboard.

Why ESP32 Distance Alarm System is Perfect for Beginners

ReasonWhy It Matters
Only 4 componentsESP32, sensor, 2 LEDs, buzzer (optional)
No soldering requiredBreadboard and jumper wires only
Teaches real physicsSpeed of sound, time-of-flight measurement
Instant feedbackLEDs light up – you see it working immediately
UsefulDesk alarm, parking sensor, social distancing monitor

For a BUET first-year student? This ESP32 Distance Alarm System is the perfect weekend project.

What You'll Need for ESP32 Distance Alarm System

Components

ComponentSpecsApprox Price (USD)
ESP32 Development BoardAny version$5.00 - $6.70
HC-SR04 Ultrasonic Sensor5V, 2cm-400cm range$1.25 - $2.10
Red LED5mm, any brightness$0.05 - $0.10
Blue LED5mm, any brightness$0.05 - $0.10
220Ω Resistors (2x)For LEDs$0.02 - $0.05 each
Passive Buzzer (Optional)5V$0.25 - $0.45
Breadboard400 points$0.85 - $1.25
Jumper WiresMale-to-female$0.40 - $0.85

Total (without buzzer): ~$8.00 - $10.50 USD – less than a pizza!

Components for an ESP32 distance alarm including an ESP32 development board on a breadboard, HC-SR04 ultrasonic sensor, LEDs, and jumper wires.
ComponentWhere to Find
ESP32 Development BoardAliExpress
HC-SR04 Ultrasonic SensorAliExpress
LED Kit (Various Colors)AliExpress
220Ω Resistors (Pack)AliExpress
Passive BuzzerAliExpress
Breadboard + Jumper KitAliExpress

Wiring ESP32 Distance Alarm System Up (10 Minutes)

HC-SR04 Ultrasonic Sensor

Sensor PinESP32 PinNotes
VCC5VNeeds 5V power
GNDGNDCommon ground
TRIGGPIO 5Send trigger pulse
ECHOGPIO 18Receive echo pulse

How the sensor works:

  • TRIG pin sends a 10µs HIGH pulse

  • Sensor shoots 8 ultrasonic bursts

  • Sound bounces back

  • ECHO pin goes HIGH for the time it took

  • ESP32 measures that time

LEDs

LEDESP32 PinThrough Resistor
Red LED Anode (+)GPIO 19220Ω resistor
Red LED Cathode (-)GNDDirect
Blue LED Anode (+)GPIO 21220Ω resistor
Blue LED Cathode (-)GNDDirect

Buzzer for ESP32 Distance Alarm System (Optional)

Buzzer PinESP32 Pin
Positive (+)GPIO 22
Negative (-)GND
Completed ESP32 distance alarm prototype on a breadboard with a glowing blue LED and HC-SR04 ultrasonic sensor.

The Science Stuff for ESP32 Distance Alarm System (But Make It Fun)

How Ultrasonic Sensors Work

Think of it like a bat or a dolphin. They scream, listen for the echo, and know how far away things are.

The HC-SR04 does the same thing:

  1. TRIGGER: ESP32 tells sensor "SCREAM NOW!"

  2. SCREAM: Sensor shoots 8 ultrasonic pulses (40kHz – too high for human ears)

  3. ECHO: Sound hits object and bounces back

  4. LISTEN: Sensor measures how long the echo took

  5. CALCULATE: Distance = (Time × 343 m/s) / 2

Why divide by 2? The sound goes there AND back. We only want the "there" distance.

Speed of Sound (The Only Math You Need)

MediumSpeed
Air (20°C)343 m/s
Air (0°C)331 m/s
Water1480 m/s
Steel5000 m/s

For room temperature, we use 0.034 cm/µs (centimeters per microsecond).

So: Distance (cm) = (Time in µs × 0.034) / 2

The code does this for you. No math degree required.

The Code (Copy-Paste Ready) ESP32 Distance Alarm System

Full code available on GitHub: [ESP32 Distance Alarm System]

How to Test It

Step 1: Upload the code to ESP32

Step 2: Open Serial Monitor (115200 baud)

Step 3: Wave your hand in front of the sensor

Step 4: Watch the LEDs and Serial Monitor

DistanceRed LEDBlue LEDBuzzer
< 30 cmONOFFBeeping
30-400 cmOFFONSilent
> 400 cmOFFOFFSilent

Troubleshooting for ESP32 Distance Alarm System

ProblemLikely CauseFix
Distance always 0ECHO pin not connectedCheck GPIO 18 connection
Distance always 400cmNo echo receivedSensor facing wrong way? Object too far?
LEDs not workingWrong polarity or missing resistorCheck anode (+) to ESP32, cathode (-) to GND
Buzzer not workingPassive vs active confusionUse tone() for passive buzzer
Serial shows random numbersPower fluctuationAdd 100µF capacitor across 5V and GND

Make It Your Own (Upgrades)

UpgradeWhat You'll NeedDifficulty
Multiple zonesAdd yellow LED for "warning" zone (30-50cm)⭐ Easy
LCD display16x2 I2C LCD – show exact distance⭐⭐ Medium
Servo reactionSG90 servo – point at the intruder⭐⭐ Medium
Data loggingSD card module – log distances over time⭐⭐⭐ Hard
Remote alertLoRa module – send alert to another room⭐⭐⭐ Hard

Real-World Applications for ESP32 Distance Alarm System

Use CaseHow It Works
Parking sensorMount on your car bumper – beeps when too close to wall
Social distancing monitorAlerts when someone gets within 6 feet
Desk intrusion alarmProtects your snacks from roommates
Liquid level sensorPoint at a water tank – measures fill level
Robot obstacle avoidanceYour robot can "see" walls and turn away

What You Learned from ESP32 Distance Alarm System

ConceptWhy It Matters
Ultrasonic sensorsMeasure distance without touching anything
pulseIn() functionMeasures time of electrical pulses
Speed of sound calculationReal physics in your code
LED indicatorsVisual feedback for users
Threshold logic"If this, then that" decision making

The ESP32 Advantage for ESP32 Distance Alarm System

Why ESP32 Instead of Arduino Uno?Benefit
Faster processorMore accurate timing
Built-in Bluetooth/WiFiAdd remote notifications later
More pinsRoom to expand
Still beginner-friendlySame Arduino code works

If you only have an Arduino Uno, the code works exactly the same – just change the pin numbers.

Project Demo- ESP32 Distance Alarm System

This video is hosted by YouTube. It loads only when you press play, and YouTube may then set cookies. Watch on YouTube

Read other blogs:

Read roborear blogs

Your Turn

This ESP32 Distance Alarm System project taught me that you don't need expensive sensors to do cool things. A $5 ultrasonic sensor, two LEDs, and an ESP32 – that's it.

Now go build it. Then break it. Then fix it and make it better.

That's how we learn.

FAQs

Frequently Asked Questions

1. Why is my HC-SR04 sensor showing random or zero distance values?

This is a very common issue, especially with ESP32.

If distance always shows 0 cm, your ECHO pin is likely not connected properly. Check that GPIO 18 is securely connected to the ECHO pin on the sensor.

If distance jumps randomly, your power supply is unstable. Add a 100µF capacitor between 5V and GND near the sensor. Also try using a phone charger instead of USB power from your computer.

If distance is stuck at 400cm, the sensor is not receiving any echo. Make sure the sensor is facing a solid object. Soft surfaces like carpet or fabric absorb sound waves instead of reflecting them.

If values fluctuate wildly, you might have multiple ultrasonic sensors interfering with each other. Only one sensor should be active at a time.

Pro tip: Test your sensor with the Serial Monitor open. Wave your hand slowly in front of it. The values should change smoothly. If they jump erratically, your power supply is likely the issue.

2. What's the maximum and minimum distance the HC-SR04 can measure?

The minimum reliable distance is 2 cm. Anything closer than that gives unstable readings.

The maximum distance specified by the manufacturer is 400 cm (4 meters).

The most reliable range is between 10 cm and 350 cm.

The accuracy is approximately plus or minus 3 mm, which is good enough for most hobby projects.

Important note: The sensor measures distance to the nearest object in its cone-shaped beam, which is about 15 to 30 degrees wide. If you have multiple objects in front of the sensor, it will return the distance to the closest one.

For better accuracy, keep the sensor pointed straight at your target. Avoid soft surfaces like carpet or fabric because they absorb sound waves. For liquid level sensing, point the sensor at the water surface at a 90-degree angle.

3. Can I use this project with an Arduino Uno instead of ESP32?

Yes, absolutely! The code works on Arduino Uno with just one small change.

The only difference is the pin numbers. Here is the pin mapping:

For ESP32: TRIG on GPIO 5, ECHO on GPIO 18, Red LED on GPIO 19, Blue LED on GPIO 21, Buzzer on GPIO 22.

For Arduino Uno: TRIG on Pin 9, ECHO on Pin 10, Red LED on Pin 11, Blue LED on Pin 12, Buzzer on Pin 13.

To use Arduino Uno, simply change these lines in the code:

#define TRIG_PIN 9#define ECHO_PIN 10#define RED_LED 11#define BLUE_LED 12#define BUZZER_PIN 13

Everything else remains identical. The pulseIn() function, the distance calculation, and the LED logic all work exactly the same on Arduino Uno.

So why use ESP32? The ESP32 gives you room to grow. You can later add WiFi notifications, Bluetooth control, or connect multiple sensors without running out of pins. But for this basic distance alarm, either board works perfectly.

Affiliate Disclosure

Some links in this ESP32 Distance Alarm System post are affiliate links. If you purchase through them, I may earn a small commission at no extra cost to you. This helps support Roborear. Thanks!

Tags

RoborearESP32 tutorialESP32 buzzerESP32 distance alarmHC-SR04 tutorialultrasonic sensor ESP32distance measurement projectESP32 LED controlArduino distance sensorDIY parking sensorbeginner robotics projectHC-SR04 with ESP32ultrasonic distance alarmESP32 projects for beginnersArduino ultrasonic sensorred blue LED indicatordistance sensor Arduino
← More articlesThanks for reading Roborear.