Bench NotesUno handbook

Measuring Distance with an HC-SR04

Trigger an ultrasonic ping, time the echo with pulseIn(), and convert it to centimetres.

IntermediateUltrasonic sensorSerial

Overview

The HC-SR04 sends a burst of 40 kHz sound and raises its Echo pin for as long as the sound takes to return. Sound travels about 0.0343 cm per microsecond, and the time covers the trip there and back, so distance = time × 0.0343 ÷ 2.

You will need

  • Arduino Uno R3
  • HC-SR04 ultrasonic module (5 V version)
  • 4 jumper wires

Wiring

Uno pinConnects toNotes
5VVCC
7Trig10 µs HIGH pulse starts a measurement
6EchoHIGH for the round-trip time
GNDGND
Wiring for Measuring Distance with an HC-SR04Arduino Uno 5V to HC-SR04 VCC; Arduino Uno D7 to HC-SR04 Trig; Arduino Uno D6 to HC-SR04 Echo; Arduino Uno GND to HC-SR04 GND.Connections (each line is one wire)Arduino UnoHC-SR045VVCCD7TrigD6EchoGNDGND
Original wiring diagram. Each line is one jumper wire; boxes on a line are series resistors.

The sketch

ultrasonic_distance.ino
const int TRIG_PIN = 7;
const int ECHO_PIN = 6;

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

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

  // Wait at most 30 ms (about 5 m round trip) for the echo
  unsigned long echoUs = pulseIn(ECHO_PIN, HIGH, 30000UL);

  if (echoUs == 0) {
    Serial.println("No echo (out of range)");
  } else {
    float distanceCm = echoUs * 0.0343 / 2.0;
    Serial.print("Distance: ");
    Serial.print(distanceCm, 1);
    Serial.println(" cm");
  }
  delay(100);
}

How the code works

The timeout in pulseIn() matters: without it the call waits up to one second when nothing reflects. Keep at least 60 ms between pings so echoes from one ping do not arrive during the next. Soft or angled surfaces may not reflect enough to measure.

Some newer modules (HC-SR04P, RCWL-1601) also run at 3.3 V; the classic module needs 5 V.

What you should observe

  • A hand 20 cm away reads about 20 cm; accuracy is typically within a centimetre or so.
  • Below about 2 cm or beyond about 4 m you will see erratic values or "No echo".