Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 37 ยท Sensors and Actuators

Ultrasonic Distance Sensor (HC-SR04)

Measure distance with the HC-SR04 and Arduino: trigger and echo timing, pulseIn(), converting microseconds to centimeters, timeouts, and filtering bad echoes.

An ultrasonic distance sensor works like a bat. It sends a short burst of sound too high for you to hear (40 kHz), waits for the echo, and measures how long the round trip took. Sound travels at about 343 meters per second in air at 20 degrees Celsius, so time becomes distance. The HC-SR04 is the cheap, popular module: it measures roughly 2 cm to 400 cm with about 3 mm resolution under good conditions.

Hardware and the Arduino IDE cannot run on this site, so the sketches are read-only. The C programs are stand-ins that run the same math on fixed sample times so you can check your understanding without a board.

Wiring and the protocol

The module has four pins: VCC (5 V), GND, TRIG and ECHO. The protocol has three steps:

  1. Pull TRIG high for at least 10 microseconds.
  2. The module sends eight 40 kHz pulses, then raises ECHO.
  3. ECHO stays high for as long as the sound took to go out and come back.
sequenceDiagram
  participant A as Arduino
  participant M as HC-SR04
  A->>M: TRIG high 10 us
  M->>M: send 8 ultrasonic pulses
  M-->>A: ECHO goes high
  Note over A,M: ECHO width = round-trip time
  M-->>A: ECHO goes low (echo received)

The Arduino measures how long ECHO stays high.

Because the sound goes out and back, divide by two: distance = time * speed / 2. With the speed of sound at 0.0343 cm per microsecond, distance_cm = time_us * 0.0343 / 2, which is about time_us / 58.

The sketch

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

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

float readDistanceCm() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  unsigned long width = pulseIn(ECHO_PIN, HIGH, 30000UL);  // timeout 30 ms
  if (width == 0) {
    return -1.0;                    // no echo: out of range
  }
  return width / 58.0;
}

void loop() {
  float cm = readDistanceCm();
  if (cm < 0) {
    Serial.println("out of range");
  } else {
    Serial.print(cm);
    Serial.println(" cm");
  }
  delay(100);
}

pulseIn(pin, HIGH, timeout) waits for the pin to go high, then times how long it stays high, in microseconds. The third argument matters: without it, a missing echo (nothing in range, or a soft object that absorbs sound) makes the call wait a full second by default and freezes your sketch. A timeout of 30,000 microseconds corresponds to about 5 meters, a bit beyond the sensor's range.

C Stand-in: echo time to distance (C)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Temperature changes the answer

Sound is faster in warmer air. A good approximation is speed = 331.3 + 0.606 * T meters per second (T in Celsius). Over a 2 m measurement this matters: at 0 C versus 30 C the same echo time differs by about 5 percent, i.e. several centimeters. If you already have a temperature sensor (see temperature and humidity sensors), you can compensate.

C Stand-in: temperature-compensated distance (C)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Dealing with bad readings

Ultrasonic sensors misbehave in predictable ways. Soft materials (clothes, foam) absorb the pulse. Angled flat surfaces bounce the echo away from the receiver. Two sensors firing together hear each other. Occasional readings are wildly wrong, or 0.

The standard cure is to take several readings and use the median, which ignores outliers (an average would be dragged toward them). Taking five readings 30 to 50 ms apart is a good compromise.

C Stand-in: median of five readings (C)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Using the library alternative

Libraries such as NewPing wrap this logic, add median helpers and work with several sensors. Writing it once by hand is still worth it: you learn what pulseIn does and can adapt to similar sensors. For how to add third-party code, see installing and managing libraries.

Practical tips

  • Mount the sensor firmly and keep the beam clear; a cable in front of it causes false short readings.
  • Wait at least 60 ms between measurements so an old echo does not confuse the next one.
  • Treat anything under 2 cm or over about 400 cm as invalid.
  • The measurement blocks your sketch for up to the timeout. If you need to do other work, see the non-blocking timing ideas in the thermostat project.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the round-trip time divided by two?

    ECHO stays high for the trip out and back, so the one-way distance is half of time multiplied by speed.
  2. 2. What does pulseIn(ECHO_PIN, HIGH, 30000) return if no echo arrives?

    With a timeout, pulseIn returns 0 when no complete pulse is measured in time. Without a timeout it waits up to one second by default.
  3. 3. Approximately how many centimeters does an echo of 5800 microseconds represent?

    Distance in cm is about time in microseconds divided by 58, so 5800 / 58 is 100 cm.
  4. 4. Why is the median better than the average for rejecting a wild echo?

    An outlier shifts an average noticeably but ends up at the edge of the sorted list, so the median is unaffected.

Summary

  • The HC-SR04 is triggered by a 10 microsecond pulse; ECHO width is the round-trip time.
  • Distance in centimeters is about width_us / 58; use a timeout in pulseIn and treat 0 as "no echo".
  • Air temperature changes the speed of sound; compensate for precise work.
  • Use the median of several readings to reject bad echoes.

Next: Servo Motors