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:
- Car parking sensors: While reversing, the sensor detects the wall approaching the bumper and beeps faster as the distance shrinks.
- Automatic hand dryers and taps: They switch on when you bring your hand close and stop when you pull it away.
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:
- VCC: 5-volt power.
- GND: Ground.
- Trig: Trigger. We send a short signal here to say "measure now."
- Echo: Echo. When the sound returns, this pin reports the time to us.
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.
- Sensor VCC → Arduino 5V
- Sensor GND → Arduino GND
- Sensor Trig → Arduino pin 9
- Sensor Echo → Arduino pin 10
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.
- Set up the wiring above (sensor + LED).
- Measure the distance inside
loop. - Write a three-level rule:
- If the distance is greater than 20 cm, keep the LED off.
- If the distance is between 10 and 20 cm, blink the LED slowly (for example, every 500 ms).
- If the distance is less than 10 cm, keep the LED on steadily.
- 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
- The HC-SR04 runs only on 5 volts, meaning USB or a small battery pack. Never connect it to mains electricity.
- This sensor is low-voltage and not dangerous on its own; even so, make your connections while the power is off.
- If you are trying to drive a motor with the sensor, do not connect the motor directly to an Arduino pin. Motors need a separate power source and a motor driver, which we will cover in the next lesson.
- When you build a circuit for the first time, ask an adult for help and check your connections twice.
Lesson summary
- An ultrasonic sensor sends out a sound pulse and measures how long its echo takes to return.
- Distance is found by multiplying the time by the speed of sound (0.0343 cm/µs) and dividing by two.
- Trig is an output that starts the measurement; Echo is an input that reports the time through
pulseIn. - Combining the measured distance with an
ifcondition lets a robot make a decision. - The sensor is low-voltage; driving a motor needs a separate power source and a motor driver.
Review questions
- What are the Trig and Echo pins of the HC-SR04 for?
- Why do we divide the measured time by two?
- What unit does the
pulseInfunction return, and what does it measure? - If the measured time is 1160 microseconds, about how many centimetres away is the object?
- Why can't we drive a motor directly from the same pin as a distance sensor?
Answers
- 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.
- 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.
pulseInreturns the time the Echo pin stays HIGH in microseconds; that is, it measures the sound's round-trip time.- 1160 × 0.0343 = 39.79; dividing by two gives about 20 centimetres.
- 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.