Measure distance with an ultrasonic sensor

Use the HC-SR04 ultrasonic sensor to measure distance in centimetres and show it in the Serial Monitor.
  • Level:Beginner
  • Duration: 40 min
  • Ages 10+
  • Platform: Arduino

What you'll need

Measure distance with an ultrasonic sensor – EEMENTOR STEM lesson

Bats find their way with sound, and so can your Arduino. The ultrasonic sensor sends out a short sound pulse that people can't hear and times how long the echo takes to come back.

What you'll learn

  • How an ultrasonic sensor measures distance
  • How to time a pulse with pulseIn()
  • How to print values to the Serial Monitor

What you need

  • UNO R3 board and USB cable
  • Ultrasonic sensor (HC-SR04)
  • Breadboard
  • 4 jumper wires

Wiring

Breadboard wiring diagram: Measure distance with an ultrasonic sensor
Breadboard view. Check each connection against the wiring table below.
Sensor pin UNO pin
VCC 5V
Trig 9
Echo 10
GND GND

The sketch

const int TRIG_PIN = 9;
const int ECHO_PIN = 10;

void setup() {
  Serial.begin(9600);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
}

void loop() {
  // Send a 10 microsecond pulse to start a measurement
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  // Time the echo (in microseconds), give up after 30 ms
  long duration = pulseIn(ECHO_PIN, HIGH, 30000);

  if (duration == 0) {
    Serial.println("Out of range");
  } else {
    // Sound travels about 0.0343 cm per microsecond, there and back
    float distanceCm = duration * 0.0343 / 2;
    Serial.print("Distance: ");
    Serial.print(distanceCm);
    Serial.println(" cm");
  }
  delay(200);
}

Upload the sketch, then open Tools → Serial Monitor and set the speed to 9600 baud. Move your hand in front of the sensor and watch the distance change.

How it works

The sound travels to the object and back, so the sketch divides the total time by two. At room temperature sound moves about 343 metres per second, which is 0.0343 cm per microsecond. The sensor works best between about 2 cm and 4 m.

Try this next

  • Add the LED from lesson 1 and switch it on when something is closer than 20 cm.
  • Open Tools → Serial Plotter to see the distance as a live graph.

Troubleshooting

  • Always "Out of range": check that Trig and Echo aren't swapped.
  • Jumpy readings: soft or angled surfaces reflect sound poorly. Point the sensor at a flat, hard object.

Build it yourself

Everything used in this lesson comes in one kit, with parts tested by our engineers.

UNO R3 Starter Kit | Arduino IDE Compatible | Free Tutorials $48.00

Shop the kit