Home › DIY Projects › Ultrasonic Distance Meter

Ultrasonic Distance Meter with Arduino and HC-SR04 (LED Alert)

Measure how far an object is, show it on the Serial Monitor and light a green, yellow or red LED like a car parking sensor. A perfect first sensor project.

  • Level: Beginner
  • Time: 30 minutes
  • Board: Arduino Uno
  • No soldering
▶ Copy code + open simulatorGet the code

What you will build

An HC-SR04 ultrasonic sensor sends out a short burst of sound that humans cannot hear and listens for the echo. The Arduino times the echo, turns that time into centimetres and shows the result. Three LEDs give an instant warning: green when the object is far (50 cm or more), yellow when it is getting close (20 to 50 cm) and red when it is too close (under 20 cm).

You will learn how to use pulseIn() to time a signal, how the speed of sound gives distance, and how to drive LEDs from simple if/else rules. Try it in the simulator first, then build it on a breadboard.

Components required

Arduino Uno R3 compatible boardArduino Uno R3 × 1The brain. Any Uno or Nano works.
View in store →
HC-SR04 ultrasonic distance sensorHC-SR04 ultrasonic sensor × 1Measures about 2 cm to 4 m.
View in store →
Three 5 mm LEDs glowing green, yellow and red5 mm LEDs × 3One green, one yellow, one red.
220 ohm resistor with red, red, brown and gold bands220 Ω resistors × 3One per LED, so the LEDs do not burn out. 220 Ω to 330 Ω is fine.
Breadboard × 1Half or full size.
View in store →
Jumper wires (male to male) × 10About 10 wires.
View in store →

Circuit diagram and connections

Tap any part in the diagram to see what it does and where it connects.

Arduino Uno9 104 3 25V GND HC-SR04 GNDRed = 5V · Black = GND · Orange = Trig · Blue = Echo

Tap a part to learn more.

Part pinArduino pinWire colour (suggested)
HC-SR04 VCC5VRed
HC-SR04 TrigD9Orange
HC-SR04 EchoD10Blue
HC-SR04 GNDGNDBlack
Green LED long leg (via 220 Ω)D4Green
Yellow LED long leg (via 220 Ω)D3Yellow
Red LED long leg (via 220 Ω)D2Red
All LED short legsGNDBlack

Arduino code

Copy this sketch into the simulator or the Arduino IDE. We wrote and tested it ourselves; you are free to use and change it.

/*
  ZEENAIX DIY Project: Ultrasonic Distance Meter with LED Alert
  Board:  Arduino Uno
  Parts:  HC-SR04 ultrasonic sensor, 3 LEDs (green, yellow, red), 3 x 220 ohm resistors
  Shows the distance on the Serial Monitor and lights an LED:
    green  = far (more than 50 cm)
    yellow = getting close (20 to 50 cm)
    red    = too close (less than 20 cm)
  Free to use and change. https://zeenaix.com
*/

const int TRIG_PIN   = 9;    // HC-SR04 Trig
const int ECHO_PIN   = 10;   // HC-SR04 Echo
const int GREEN_LED  = 4;
const int YELLOW_LED = 3;
const int RED_LED    = 2;

const int NEAR_CM = 20;      // red below this distance
const int MID_CM  = 50;      // yellow below this distance

void setup() {
  Serial.begin(9600);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  pinMode(GREEN_LED, OUTPUT);
  pinMode(YELLOW_LED, OUTPUT);
  pinMode(RED_LED, OUTPUT);
  Serial.println("ZEENAIX distance meter ready");
}

// Sends one ultrasonic ping and returns the distance in cm (-1 = no echo)
long readDistanceCm() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);     // 10 microsecond pulse starts a measurement
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  // Echo stays HIGH for as long as the sound took to go out and come back.
  unsigned long duration = pulseIn(ECHO_PIN, HIGH, 30000UL);  // give up after 30 ms
  if (duration == 0) {
    return -1;
  }
  // Sound travels about 0.0343 cm per microsecond, there and back,
  // so distance = duration * 0.0343 / 2, which is close to duration / 58.
  return duration / 58;
}

void showLeds(long cm) {
  bool red    = (cm >= 0 && cm < NEAR_CM);
  bool yellow = (cm >= NEAR_CM && cm < MID_CM);
  bool green  = (cm < 0 || cm >= MID_CM);
  digitalWrite(RED_LED,    red    ? HIGH : LOW);
  digitalWrite(YELLOW_LED, yellow ? HIGH : LOW);
  digitalWrite(GREEN_LED,  green  ? HIGH : LOW);
}

void loop() {
  long cm = readDistanceCm();
  if (cm < 0) {
    Serial.println("Out of range");
  } else {
    Serial.print("Distance: ");
    Serial.print(cm);
    Serial.println(" cm");
  }
  showLeds(cm);
  delay(200);   // about 5 readings per second
}

Step-by-step instructions

A. Try it in the free simulator (5 minutes)

  1. Open the ZEENAIX Arduino Simulator and choose Blank editor with the Arduino Uno board.
  2. Delete the starter code, then paste the sketch from the code section.
  3. Tap + Add and place an HC-SR04 ultrasonic sensor, three LEDs (green, yellow, red) and three 220 Ω resistors.
  4. Draw the wires exactly as in the connection table above.
  5. Press the green ▶ run button and open Serial. You should see ZEENAIX distance meter ready and then a new distance reading about five times a second.
  6. While it runs, tap the sensor and move its distance slider. Watch the LED change from green to yellow to red as the object comes closer.

B. Build it on a breadboard (25 minutes)

  1. Push the HC-SR04 into the breadboard with its two round "eyes" facing forward and nothing in front of them.
  2. Place the three LEDs in a row. The long leg is the positive side (anode). Put a 220 Ω resistor from each long leg to its own empty row.
  3. Connect the HC-SR04: VCC to 5V, GND to GND, Trig to pin 9 and Echo to pin 10.
  4. Connect the resistor rows to pins 4 (green), 3 (yellow) and 2 (red), and join all three short LED legs to GND.
  5. Plug the Uno into your computer, open the Arduino IDE, select Tools › Board › Arduino Uno and the right COM port, paste the code and click Upload. Boards with the CH340 chip may need the CH340 USB driver the first time.
  6. Open Tools › Serial Monitor at 9600 baud. Hold your hand or a book in front of the sensor and move it closer and further away.

Try it here: what the LEDs will do

Distance: 35 cm

This uses the same rules as the sketch: under 20 cm is red, 20 to 50 cm is yellow, 50 cm or more is green.

How it works

Sound travels through air at about 343 metres per second at room temperature, which is 0.0343 cm every microsecond. When the Arduino sets Trig HIGH for 10 microseconds, the HC-SR04 sends eight quick 40 kHz pulses and sets Echo HIGH until the echo comes back. pulseIn() measures how long Echo stayed HIGH.

The sound travels to the object and back, so the distance is duration × 0.0343 ÷ 2. That is the same as dividing the time by about 58, which is why the code uses duration / 58. For example, an echo of 2,030 microseconds means 2030 ÷ 58 = 35 cm. If no echo arrives within 30 ms, the sketch prints Out of range and shows green.

Tested: we compiled this sketch for the Arduino Uno and ran it in an AVR simulation with objects at 100, 35, 10 and 250 cm. It printed 99, 34, 9 and 248 cm and lit green, yellow, red and green as expected. A reading 1 cm lower than the true distance is normal, because the code rounds down.

Real-life uses of an ultrasonic distance sensor

Car parking sensor

Mount the sensor on the back wall of a garage. The LED turns red when the bumper is close, so you stop at the same spot every day. Add a buzzer for a beep.

Water tank level

Fix the sensor on the lid of an overhead tank, facing down. The distance to the water tells you how full the tank is, so you can switch off the motor before it overflows.

Obstacle-avoiding robot

Put the sensor on the front of a robot car. When something is closer than 20 cm, the robot stops and turns. This is a common school and college project.

Touch-free dustbin or sanitizer

When a hand comes within about 15 cm, a servo opens the lid or a pump gives a squirt of sanitizer, with no touching.

Safe-distance reminder

Place it on a desk to warn when a child sits too close to a screen, or at a shop counter to remind customers to keep a queue distance.

Troubleshooting

  • Always "Out of range" or 0: check that Trig and Echo are not swapped and that VCC goes to 5V, not 3.3V.
  • Readings jump around: point the sensor at a flat, hard surface. Soft cloth, foam and sharp angles absorb or scatter the sound.
  • An LED never lights: turn the LED around (long leg towards the resistor and pin) and check the resistor is in the same row.
  • Nothing in the Serial Monitor: set the baud rate to 9600 and make sure the correct COM port is selected.

Frequently asked questions

What is the range of the HC-SR04?

About 2 cm to 400 cm. Below 2 cm the echo returns too fast to measure, and beyond about 4 m it becomes too weak, so readings are most reliable between 5 cm and 200 cm.

Can I use an ESP32 instead of an Arduino Uno?

Yes, but the ESP32 uses 3.3V logic and the HC-SR04 Echo pin outputs 5V. Use a simple voltage divider (for example 1 kΩ and 2 kΩ resistors) on the Echo line to protect the ESP32.

Why divide by 58?

Sound needs about 29 microseconds to travel 1 cm, and it has to go there and back, so each centimetre of distance adds about 58 microseconds to the echo time.

Do I need to buy parts to try this?

No. You can run the whole project in the free ZEENAIX simulator first, then buy only the parts you need when you are ready to build it.

Build it for real

Get the Arduino Uno, HC-SR04 sensor, breadboard and jumper wires from the ZEENAIX store, delivered across India.

▶ Copy code + open simulatorMore DIY projects