Sharjah, UAE GST
Home/ Projects/ Lesson 1: Measure Distance with Sound
Lesson 1 of 9 Sensing Beginner ◎ 30-45 min

Lesson 1: Measure Distance with Sound

Wire the ultrasonic sensor, then read the distance to a book on your computer screen and check it against a ruler.

Arduino Ultrasonic Distance & Parking Learning Kit
One of 9 projects in the Arduino Ultrasonic Distance & Parking Learning Kit — the parts below are from that kit.

Before you start

Time
30-45 min
Do these first
Start here: Blink uploaded and the L light blinking
On your own
You can do this lesson on your own. For your very first wiring, an adult nearby is a good idea.

Exact parts

PartHow many
UNO R3 + USB cable1
400-point breadboard1
HC-SR04 distance sensor1
Male-to-male jumper wires6
A ruler or tape measure, and a book or flat card (yours)1

Not in the box

Nothing extra - just the kit and your computer.

What you build and learn

  • How the HC-SR04 measures distance with sound
  • Wiring a module by its labels: VCC, TRIG, ECHO, GND
  • Reading numbers in the Serial Monitor
  • Why you average several readings instead of trusting one

One "eye" of the sensor sends a short click of ultrasound; the other listens for the echo. The UNO starts it with a 10-microsecond pulse on TRIG.

The sensor then holds ECHO high for as long as the sound took to get there and back. pulseIn() measures that time in microseconds.

Sound needs about 58 microseconds for every centimetre of distance, there and back, so time ÷ 58 = centimetres.

Each line on the screen is the average of 5 pings. One ping can be off; the average of five is steadier. The second number says how many of the 5 echoes came back.

New words

Ultrasound
Sound too high for people to hear. The HC-SR04 uses 40 kHz.
Echo
Sound that bounces back off an object.
Breadboard
A board with hidden metal strips. Parts in the same short row of holes are connected.
Rail
The long lines of holes along the edge of the breadboard: red line (+) for 5V, blue line (−) for GND.
Serial Monitor
A window in the Arduino IDE (Tools → Serial Monitor) that shows the text the UNO sends.

What this project uses

Every item is in the kit — nothing extra to buy.

Build this with

Arduino Ultrasonic Distance & Parking Learning Kit

All 9 parts in one box, with this project and 8 more to build from them.

AED 85.00 See the kit
Need only these parts? Order them loose · from AED 78.30
Used in this project tick what you still need
Selected parts AED 78.30

One of each part. Packs (resistor assortment, jumper wires) already hold more than a single build needs. a ruler and a flat card or book (yours): included in the kit, ask us for it loose. Delivery is AED 20, free on orders AED 100+.

Connections

Unplug USB before you change any wire. Pin names are the labels printed on the board.

Lesson 1: Measure Distance with Sound - connection diagram with labelled pins
Connection diagram, drawn from this lesson's pin plan - not a photo of a tested build. Tap to open it full size. The table below says the same thing in words.
Part / pinConnect toNote
UNO 5V+ rail (red line)Powers the sensor
UNO GND− rail (blue line)Shared ground for everything
HC-SR04 VCC+ rail (5V)Go by the labels printed on the sensor
HC-SR04 TRIGUNO pin 9
HC-SR04 ECHOUNO pin 10
HC-SR04 GND− rail (GND)

Step by step

One thing at a time. Tick nothing off until it matches the diagram.

  1. Unplug the USB cable from the computer.Watch out: Always unplug the USB cable before you add, move or remove a wire.
  2. Put the breadboard next to the UNO. Find the red (+) and blue (−) lines along its edge: those are the rails.
  3. Connect a jumper wire from the UNO 5V pin to the + rail, and one from a UNO GND pin to the − rail.Watch out: Never join the + rail straight to the − rail.
  4. Push the HC-SR04 into the breadboard near one end, with its two round "eyes" facing out over the edge and each of its 4 pins in its own row.Watch out: Read the labels printed by the pins: VCC, Trig, Echo, Gnd. Some sensors print them in a different order.
  5. Wire VCC to the + rail, GND to the − rail, TRIG to UNO pin 9 and ECHO to UNO pin 10.
  6. Check every wire against the diagram and the table, then plug the USB cable back in.Watch out: If anything gets hot or smells, unplug straight away.
  7. Copy the Lesson 1 code below into the Arduino IDE and click Upload (→).
  8. Open Tools → Serial Monitor and set the speed to 9600 baud.
  9. Lay a ruler on the table from the front of the sensor. Hold a book upright at 10, 20, 30 and 50 cm and write down the number shown each time.

Sketch for this project

Written for the board in the kit. Copy it into the Arduino IDE; change the pin numbers if you wire it differently.

lesson1_measure_distance.ino arduino
/*
  DIY KIT - Arduino Ultrasonic Distance & Parking Learning Kit
  Lesson 1 of 9: Measure Distance with Sound

  WIRING (unplug the USB cable before you wire)
    HC-SR04 VCC  -> 5V   (+ rail)
    HC-SR04 TRIG -> UNO pin 9
    HC-SR04 ECHO -> UNO pin 10
    HC-SR04 GND  -> GND  (- rail)

  WHAT SHOULD HAPPEN
    Open Tools > Serial Monitor and set it to 9600 baud. Twice a second a
    new line shows the distance to whatever is in front of the sensor, and
    how many of the 5 pings came back. Hold a book in front of the sensor
    and compare the number with a ruler.
*/

const int TRIG_PIN = 9;    // we send the "click" from here
const int ECHO_PIN = 10;   // the sensor answers on this pin

const int SAMPLES = 5;                         // pings per line - try 1 and see the numbers jump
const unsigned long ECHO_TIMEOUT_US = 30000;   // give up after 30 ms (about 5 m there and back)
const int MIN_CM = 2;                          // closer than this the sensor cannot measure
const int MAX_CM = 400;                        // further than this is out of range

int lineNumber = 0;

// One measurement in centimetres, or 0 if no echo came back.
long readOnceCm() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);   // a 10-microsecond pulse starts one measurement
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  // pulseIn() times how long ECHO stays HIGH: the sound's trip there and back.
  unsigned long us = pulseIn(ECHO_PIN, HIGH, ECHO_TIMEOUT_US);
  if (us == 0) return 0;          // no echo

  long cm = us / 58;              // sound needs about 58 microseconds per cm, there and back
  if (cm < MIN_CM || cm > MAX_CM) return 0;
  return cm;
}

void setup() {
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  Serial.begin(9600);
  Serial.println("Lesson 1: Measure Distance with Sound");
  Serial.println("line, distance_cm, echoes (out of 5)");
}

void loop() {
  long total = 0;
  int echoes = 0;

  for (int i = 0; i < SAMPLES; i++) {
    long cm = readOnceCm();
    if (cm > 0) {             // only count pings that came back
      total = total + cm;
      echoes = echoes + 1;
    }
    delay(60);                // let the last echo die away before the next ping
  }

  lineNumber = lineNumber + 1;
  Serial.print(lineNumber);
  Serial.print(", ");
  if (echoes > 0) {
    long average = total / echoes;  // the average of the pings that came back (whole cm)
    Serial.print(average);
  } else {
    Serial.print("no echo");
  }
  Serial.print(", ");
  Serial.println(echoes);

  delay(200);
}
ℹCompiler-checked for Arduino UNO (0 warnings) and run in the kit simulator. Pins match the lesson diagram. Not yet bench-tested on the shipped parts.

Upload it

  1. Click Copy (or Download .ino and open the file).
  2. In the Arduino IDE choose File → New Sketch, select everything in it and paste.
  3. Check the bottom of the window says Arduino Uno and your port (Start here, step 5).
  4. Click Upload (the → arrow) and wait for Done uploading.

How the code works

In the codeWhat it does
const int TRIG_PIN = 9;Names for the two sensor pins. If you ever move a wire, change only this number.
readOnceCm()Our own function: one ping. It sends the 10 µs pulse, times the echo with pulseIn(), divides by 58 and returns centimetres - or 0 if no echo came back.
ECHO_TIMEOUT_US = 30000pulseIn() gives up after 30 ms. Without it the program could wait a long time when nothing is in front.
for (int i = 0; i < SAMPLES; i++)Repeats the ping 5 times, adding up the ones that came back. Then it prints total ÷ echoes: the average.

Change it and see

Change: Change SAMPLES from 5 to 1 and upload again.What happens: Each line is now one ping: the numbers jump about more.
Change: Change delay(200) at the end to delay(1000).What happens: A new line appears about once a second instead of twice.

What you should see or hear

  • A title line, then a new line about twice a second, like 7, 30, 5: line number, distance in cm, echoes out of 5.
  • With a book 10-50 cm away, the distance is usually within a few cm of the ruler.
  • Point it at the ceiling or an open space and you may see "no echo, 0".

If it doesn't work

ProblemWhat to check
It always says no echoUnplug USB. Check VCC to the + rail, GND to the − rail, TRIG to pin 9 and ECHO to pin 10 - by the labels on the sensor, not their position. Point it at a big flat object 20-50 cm away.
The number is 0 or "no echo" even close upNothing may be in the beam: hold the book square to the sensor, not tilted. Check ECHO is on pin 10 and TRIG on pin 9, not swapped.
The distance is always a few cm too bigMeasure from the front of the sensor's eyes, not the back of the board. Small errors are normal - Lesson 5 measures them.
Nothing or strange symbols in the Serial MonitorSet the speed in the corner of the Serial Monitor to 9600 baud. Close the Serial Plotter if it is open.
The upload failsSee Start here, step 6: "If the upload fails".

Small experiment

Measure the same book at 30 cm five times, moving it away and back each time. How far apart are your five numbers?

Check what you learned

Why can people not hear the HC-SR04?

It uses ultrasound - 40 kHz, too high for human ears.

The echo took 1160 microseconds. How far away is the object?

1160 ÷ 58 = 20 cm.

Why does each line use 5 pings?

The average of several pings is steadier than one ping.

▶In the simulator: In the simulator a slider sets the distance, so the numbers are perfectly steady and every ping comes back. A real sensor wobbles by a centimetre or two.

Next

  • Lesson 2 adds three LEDs that show how close the book is. Leave the sensor where it is.

Stuck?

Most problems are one wire in the wrong hole. Check these first:

  1. Unplug, then compare every wire with the lesson's diagram and table. One pin off is the most common problem.
  2. Sensor: are VCC, TRIG, ECHO and GND wired by their labels, with TRIG on 9 and ECHO on 10?
  3. LEDs: is the long leg on the resistor side?
  4. Is the − rail connected to a UNO GND pin, and the + rail to 5V?
  5. Serial Monitor: is it set to 9600 baud (and "New Line" when you type commands)?
  6. Upload problems: is Tools → Board set to Arduino Uno and Tools → Port to your UNO? (Start here, step 5.)
Still stuck? Ask us on WhatsApp. Send this message with a photo of your wiring - it tells us exactly where you are.
Hi DIY KIT, I'm stuck on the Arduino Ultrasonic Distance & Parking Learning Kit.
Lesson: __
Step number: __
What should happen: __
What happens instead: __
Error message (copied exactly): __
I'll attach a photo of my wiring.
Message us on WhatsApp

More from this kit

All projects →

Bot
ECHO
Online — usually replies instantly
Catalog assistant: verify final stock/price on the product page before checkout.