Home · Academy · Robotics & Coding · Arduino · The Ultrasonic Distance Sensor

The Ultrasonic Distance Sensor

Learn to measure distance with the HC-SR04 and decide based on distance.

LESSON COMPASS

What will you use this page for?

Core idea

An ultrasonic distance sensor lets us work out how far away an object is, in centimetres, by measuring how long a sound wave takes to bounce back.

Evidence to produce

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

Control trap

Mixing up the Trig and Echo pins Trig is an output ( OUTPUT ) and Echo is an input ( INPUT ). If you swap the wires or the pinMode lines, the sensor will not read anything or will always return 0. Forgetting to divide the time by two Because the sound travels there and back, the measured time covers a double journey.…

Next connection

Motor Driver: We will learn to safely spin a DC motor with a separate power source and a driver board, and to turn the distance sensor's decision into movement.

Module sources: Python Tutorial · Arduino Learn

LevelBeginner
Age10–16
Duration30–45 min
PrerequisiteServo Control
ContentStandard lesson · 1,439 words
Last updated

One-sentence summary

An ultrasonic distance sensor lets us work out how far away an object is, in centimetres, by measuring how long a sound wave takes to bounce back.

Why does it matter?

Before a robot can stop without hitting a wall, it needs to answer one question: "is something in front of me, and how far away is it?" A person looks with their eyes; a robot "sees" with a distance sensor.

An ultrasonic sensor uses the same idea bats use to find their way in the dark: send out a sound, listen for the echo, and calculate distance from the time that passes. This method is cheap, safe and runs on low voltage. That is why it is one of the most popular sensors in beginner robotics.

We meet this idea in everyday life in two places:

The HC-SR04 sensor we will use in this lesson does exactly this job, and it works with just a few connections to an Arduino.

How does the sensor work?

Send a sound, listen for the echo

The HC-SR04 has two small cylinders. One is the transmitter (it sends the sound) and the other is the receiver (it listens for the echo). The sensor sends out a sound pulse at a frequency too high for humans to hear (ultrasonic). That sound hits an object and bounces back.

The sensor has four pins:

Turning time into distance

Here is the key idea: we know the speed of sound in air, roughly 343 metres per second. Converted into the unit the sensor uses, sound travels about 0.0343 centimetres every microsecond.

The sensor gives us the total travel time. But because the sound travels to the object *and* back, this time covers twice the distance. So we divide by two:

distance = (round-trip time × 0.0343) / 2

For example, if the time is 600 microseconds: 600 × 0.0343 = 20.58; dividing by 2 means the object is about 10 centimetres away.

Measuring with Arduino

Wiring

Parts needed: one Arduino Uno, one HC-SR04 sensor, and four jumper wires.

The trigger pulse and pulseIn

To take a measurement, we send a short 10-microsecond HIGH signal to the Trig pin. Then the pulseIn function measures, in microseconds, how long the Echo pin stays HIGH. pulseIn waits for the signal to start and, as soon as it ends, returns the time that passed.

const int trigPin = 9;
const int echoPin = 10;

void setup() {
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  long duration = pulseIn(echoPin, HIGH);
  float distance = duration * 0.0343 / 2;

  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");
  delay(200);
}

After you upload the code, open the Serial Monitor at 9600 baud. As you move your hand closer to and farther from the sensor, you will see the number change.

Making a decision based on distance

When we combine the measured distance with a condition, the robot can make a decision. The sketch below turns on an LED if the object is closer than 10 centimetres; it is the simplest version of a parking sensor's "too close" warning. For the LED, connect it to pin 4 through a 220-ohm resistor.

const int trigPin = 9;
const int echoPin = 10;
const int ledPin = 4;

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  long duration = pulseIn(echoPin, HIGH);
  float distance = duration * 0.0343 / 2;

  if (distance < 10) {
    digitalWrite(ledPin, HIGH);
  } else {
    digitalWrite(ledPin, LOW);
  }
  delay(100);
}

The measuring logic in these two sketches is exactly the same; we only added a decision step to the second one. In robotics projects that decision is usually not "turn on an LED" but "stop the motors or change direction." We will add the motor driver in the next lesson.

Mini project

Build your own parking sensor. The goal is a warning that speeds up as the object gets closer.

  1. Set up the wiring above (sensor + LED).
  2. Measure the distance inside loop.
  3. Write a three-level rule:
  1. Move your hand slowly closer and watch the warning change.

Tip: For blinking, you can turn the LED on with digitalWrite, wait with delay, and turn it off again. Later you can try replacing that wait with non-blocking timing using millis.

Common mistakes

Mixing up the Trig and Echo pins

Trig is an output (OUTPUT) and Echo is an input (INPUT). If you swap the wires or the pinMode lines, the sensor will not read anything or will always return 0.

Forgetting to divide the time by two

Because the sound travels there and back, the measured time covers a double journey. If you do not divide, every distance you measure comes out twice the real value.

Using the wrong unit

You must use the speed of sound in centimetre-microsecond units (0.0343). Mixing it up with metres or milliseconds gives a meaningless result.

Measuring too often

If you do not put a small delay between measurements, an old echo can mix into a new reading. A short wait (100–200 ms) makes the readings more stable.

Safety note

Lesson summary

Review questions

  1. What are the Trig and Echo pins of the HC-SR04 for?
  2. Why do we divide the measured time by two?
  3. What unit does the pulseIn function return, and what does it measure?
  4. If the measured time is 1160 microseconds, about how many centimetres away is the object?
  5. Why can't we drive a motor directly from the same pin as a distance sensor?

Answers

  1. Trig is the trigger output that tells the sensor to "measure now"; Echo is the input that reports the elapsed time when the echo returns.
  2. Because the sound travels to the object and back, the measured time covers twice the distance; we divide by two to get the real distance.
  3. pulseIn returns the time the Echo pin stays HIGH in microseconds; that is, it measures the sound's round-trip time.
  4. 1160 × 0.0343 = 39.79; dividing by two gives about 20 centimetres.
  5. A motor draws far more current than an Arduino pin can supply and could damage the pin; that is why it needs a separate power source and a motor driver.

Source and verification note

For “The Ultrasonic Distance Sensor”, verification focuses on whether the relationship between How does the sensor work? and Turning time into distance remains consistent across examples. Pin, voltage and current limits can differ between Arduino-compatible boards. Compiling code does not guarantee a safe circuit; loads such as motors and servos require a suitable driver and external power where appropriate.

Next lesson

Motor Driver: We will learn to safely spin a DC motor with a separate power source and a driver board, and to turn the distance sensor's decision into movement.

Start QuizBack to Arduino
QUESTION POOL

Reinforce this lesson with 10 questions

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