Rishabh Kataria

How ultrasonic sensors measure distance with Arduino

By Rishabh Kataria ·

An HC-SR04 ultrasonic sensor measures distance by timing an echo: it sends a burst of 40 kHz sound, waits for it to bounce back, and the round-trip time tells you how far away the object is. It works from about 2 cm to 4 m and costs very little, which is why the Setu smart cane uses two of them.

The maths

Sound travels at about 343 metres per second in air at 20 °C, which is 0.0343 cm per microsecond. The echo goes out and back, so divide by two:

distance (cm) = echo time (µs) × 0.0343 ÷ 2

An echo of 1,000 µs means about 17 cm.

Wiring

HC-SR04 pin Arduino
VCC 5V
GND GND
Trig Digital pin 9
Echo Digital pin 10

Code

const int TRIG = 9;
const int ECHO = 10;

void setup() {
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT);
  Serial.begin(9600);
}

float readCm() {
  digitalWrite(TRIG, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG, HIGH);      // a 10 µs pulse starts a measurement
  delayMicroseconds(10);
  digitalWrite(TRIG, LOW);

  // Wait at most 30 ms (about 5 m) so a missing echo never blocks the loop
  unsigned long us = pulseIn(ECHO, HIGH, 30000);
  if (us == 0) return -1;        // nothing in range
  return us * 0.0343 / 2;
}

void loop() {
  Serial.println(readCm());
  delay(60);                     // let old echoes die out
}

Running two sensors

Setu points one sensor at the ground and one at upper-body height. If both fire at once, one can hear the other's echo. The fix is simple: fire them one after the other, with about 60 ms between readings.

Turning distance into a warning

To make a vibration motor buzz harder as obstacles get closer, map distance to a PWM value:

int strength = map(constrain(cm, 20, 150), 150, 20, 0, 255);
analogWrite(MOTOR_PIN, strength);

Drive the motor through a transistor (for example a 2N2222 or a ULN2003) with a flyback diode, never straight from the Arduino pin.

Common problems