Home · Academy · Robotics & Coding · Sensors and Actuators · Project: Distance Alarm System

Project: Distance Alarm System

Build a filtered, calibrated system that warns when an object comes too close, using a distance sensor.

PROJECT COMPASS

What will you use this page for?

Core idea

In this project we use a distance sensor to build a small system that warns us with an LED and a buzzer when an object comes closer than a limit we choose; along the way we pick a threshold, filter out bad readings, and test and fix the system.

Evidence to produce

Complete the page task with your own input, test conditions and reasoning.

Control trap

Never setting a threshold If you do not compare the sensor number to a threshold, the system cannot decide. There must always be a "closer than this" condition. Not putting the measurement in a loop Distance changes constantly. If you measure only once at the start, the system misses the movement; the measurement must…

Next connection

The micro:bit module: In this module we will start turning the sensor and output ideas we learned here into real, working little projects by programming them on the micro:bit.

Module sources: Python Tutorial · Arduino Learn

LevelBeginner
Age10–16
Duration45–75 min
PrerequisiteProject: Automatic Night Light
ContentProject guide · 2,044 words
Last updated

One-sentence summary

In this project we use a distance sensor to build a small system that warns us with an LED and a buzzer when an object comes closer than a limit we choose; along the way we pick a threshold, filter out bad readings, and test and fix the system.

Why does it matter?

In the previous project we watched a sensor value (a light sensor) and switched an output (a lamp) on automatically. Now we take the same idea further: this time what we measure is distance, and the response is a warning.

A distance alarm is a common real-world pattern: "if something gets too close, let me know." You already see it in everyday life:

In this project you practise reading a sensor, comparing that reading to a threshold, cleaning up noisy measurements, and testing a system from start to finish. These are also the foundation of the larger robot and automation projects you will build later.

What will we build?

The idea of the system

The job of the system, in one sentence: If an object in front of the sensor comes closer than the limit we choose, the LED lights up and the buzzer sounds; when the object moves away, both go quiet.

We call that limit the threshold — the distance at which we say "closer than this means danger." If we choose 15 centimetres, any object closer than 15 centimetres triggers the warning.

In this project the board is not a moving robot; it sits on the table and only measures and warns. That makes it a safe, easy first project.

Materials list

All parts are low voltage. Mains electricity or a wall socket is never used.

Materials list table
PartQtyNote
micro:bit or Arduino board1Pick a sensor that matches the board's voltage
Ultrasonic distance sensor1HC-SR04 style; with TRIG and ECHO pins
Active buzzer (3–5 V)1Sounds directly, no extra circuit
LED (red)1Long leg is the plus (+) side
Resistor1330 Ω, limits current for the LED
Breadboard1For solderless connections
Jumper wires6–8Male-to-male / male-to-female
USB cable or battery pack1Low-voltage power only

Schematic (in text)

Below we describe the connections in words. [ ] shows a part and ─── shows a wire. Every part shares the same ground (GND), the common "zero" point of the electronics.

[Board 3–5V] ─── [Sensor VCC]
[Board GND]  ─── [Sensor GND] ─── [Buzzer −] ─── [LED short leg −]
[Board P0]   ─── [Sensor TRIG]      (start-measurement signal)
[Board P1]   ─── [Sensor ECHO]      (echo return signal)
[Board P2]   ─── [Buzzer +]
[Board P8]   ─── [Resistor 330Ω] ─── [LED long leg +]

Reading order: the board tells the sensor to "measure" through TRIG, the sensor sends a sound wave, and when the wave returns the ECHO pin reports back. The board works out the distance from that time, then keeps the buzzer (P2) and LED (P8) pins on or off.

The logic of the code: warn when the threshold is crossed

The number from the sensor does nothing on its own. The real work is looking at it and making a decision. For this we use the condition structure from the Algorithms lesson: if the distance is below the threshold, warn; otherwise, stay quiet.

Pseudocode

Start
threshold = 15   (centimetres)
Repeat forever:
  distance = read the sensor
  If distance is less than threshold
    turn on the buzzer
    turn on the red LED
  Otherwise
    turn off the buzzer
    turn off the LED
End

Notice the measurement happens again and again inside a loop, because the object can move at any moment. If we measured only once, the system could not see the changing environment.

micro:bit-style example

In place of read_distance() you use the block or function that fits your sensor; the logic stays the same.

threshold = 15                   # centimetres

while True:
    distance = read_distance()   # read centimetres from the sensor
    if distance < threshold:
        buzzer_on()              # object is too close
        led_on()
    else:
        buzzer_off()             # the way is clear
        led_off()

Threshold, filtering and calibration

In its simplest form the system works, but real sensors are a little "noisy." Here we add three ideas that make it more reliable.

Choosing the threshold well

If the threshold is too large (say 100 centimetres), the system beeps all the time; everything in the room counts as "close." If it is too small (say 2 centimetres), no warning comes until the object almost touches the sensor. A good threshold is useful but does not overwhelm you — you find it by experimenting.

Filtering: don't trust a single bad reading

Ultrasonic sensors sometimes return a very small or very large number for no reason. This is called noise. We do not want the buzzer sounding for nothing because of one wrong reading. The fix: take a few measurements and use their median (the middle value), so an occasional extreme value cannot spoil the decision.

distance1 = read the sensor
distance2 = read the sensor
distance3 = read the sensor
distance = the median of these three values
If distance is less than threshold
  warn

Preventing flicker: two thresholds

If an object sits right at the threshold, the system can switch on and off very quickly. We smooth this with two thresholds (hysteresis): let the warning start at 15 centimetres, but not switch off until the object moves back past 20 centimetres.

Calibration

After placing the sensor, measure a known distance (say 20 centimetres with a ruler) and check the screen. If it is always off by 2–3 centimetres, adjust your threshold to match. Tuning a sensor against the real world is called calibration.

Testing, a bug and improvements

Test scenarios

Once the system is built, try each case:

A bug and its fix

A very common problem during setup is this: the buzzer sounds by itself now and then, even when there is nothing in front of the sensor.

Symptom: The buzzer beeps at random with no object nearby.

1. Watch the reading:
   Print the distance to the screen. If you now and then
   see an extreme value like 2 or 400, that is a noise reading.

2. Why does it happen?
   A single measurement is sometimes wrong; the system looks
   at that wrong value, thinks "close!" and triggers the buzzer.

3. Fix — filtering:
   Take the median of three readings; do not trust one reading.

4. Fix — sensible range:
   Ignore values outside the sensor's usable range
   (for example below 2 cm or above 400 cm).

Most of the time the fix is filtering. Change one thing at a time and try again, so you can see which change solved the problem. It is normal for it not to work perfectly on the first try; finding and fixing the bug is the most instructive part of this work.

Improvement ideas

Once the basic system works, you can try:

Mini practice

Complete this task on paper:

You are designing a system for a quiet study desk in a library: when someone comes closer than 30 centimetres to the desk, a soft light should turn on, but there should be no sound. Fill in the blanks in the pseudocode below:

threshold = ____
distance = read the sensor
If distance ____
  ____
Otherwise
  ____

Questions:

Common mistakes

Never setting a threshold

If you do not compare the sensor number to a threshold, the system cannot decide. There must always be a "closer than this" condition.

Not putting the measurement in a loop

Distance changes constantly. If you measure only once at the start, the system misses the movement; the measurement must repeat inside a loop.

Trusting a single reading

A single measurement is sometimes wrong; without filtering, the buzzer sounds for nothing. Use the median of a few measurements.

Forgetting the common ground

If the sensor, buzzer, LED and board do not share the same GND line, the system will not work properly. All the minus sides must connect to the common ground.

Safety note

Lesson summary

Check questions

  1. What does "threshold" mean in this system, and what is it for?
  2. Why do we need to take the measurement again and again inside a loop?
  3. The buzzer sounds now and then with nothing in front of the sensor. What is the likely cause, and how would you fix it?
  4. What happens if you choose a threshold that is too large (for example 100 centimetres)?
  5. Why is a wall socket or mains electricity never used in this project?

Answers

  1. The threshold is the limit distance at which we say "closer than this means danger"; it decides when the warning begins.
  2. Because the object's position changes constantly. If we measure only once we cannot see the movement; the loop keeps the distance up to date.
  3. The likely cause is a single noisy reading; the sensor occasionally returns a very small value and the system thinks it is "close." Fix it by taking the median of a few readings and ignoring values outside the sensible range (filtering).
  4. The system beeps almost constantly; everything counts as "close" and the warning becomes useless. The threshold should be pulled back to a smaller, meaningful value.
  5. Mains electricity is high voltage and dangerous. In learning projects we use only low-voltage sources such as USB, micro:bit or batteries.

Source and verification note

For “Project: Distance Alarm System”, verification focuses on whether the relationship between What will we build? and Materials list remains consistent across examples. Sensor readings can change with the model, supply voltage and environment. Thresholds in the lessons are therefore examples; a real project should use a measurement table and calibration.

Next lesson

The micro:bit module: In this module we will start turning the sensor and output ideas we learned here into real, working little projects by programming them on the micro:bit.

Start QuizBack to Sensors and Actuators
QUESTION POOL

Reinforce this lesson with 10 questions

This lesson has a pool of 20 questions. Each attempt selects 10 and reshuffles the choices.