How to use an HC-SR04 ultrasonic sensor for accurate distance measurement

Asked 2 weeks ago Modified 3 days ago Viewed 7 times
How to use an HC-SR04 ultrasonic sensor for accurate distance measurement

The HC-SR04 is the cheapest reliable way to measure distance with a microcontroller. It works by emitting a 40kHz ping and timing the echo's return. Effective range: about 2cm to 4m, with ±3mm accuracy in the sweet spot.

Parts

  • HC-SR04 ultrasonic module
  • Arduino UNO/Nano
  • 4 × jumper wires

Wiring

  • HC-SR04 VCC → 5V (the chip needs 5V — it does NOT work reliably on 3.3V)
  • HC-SR04 GND → GND
  • HC-SR04 TRIG → Arduino D9
  • HC-SR04 ECHO → Arduino D10

How it works

1. Pull TRIG HIGH for 10µs to fire the ping.
2. ECHO goes HIGH the moment the ping leaves, and LOW the moment a return is detected.
3. Measure the HIGH duration with pulseIn().
4. Distance in cm = duration (µs) ÷ 58.
(Speed of sound ≈ 343 m/s, round-trip, gives that 58 constant.)

Minimal sketch

void setup() {
  Serial.begin(9600);
  pinMode(9, OUTPUT); pinMode(10, INPUT);
}
void loop() {
  digitalWrite(9, LOW);  delayMicroseconds(2);
  digitalWrite(9, HIGH); delayMicroseconds(10);
  digitalWrite(9, LOW);
  long d = pulseIn(10, HIGH, 25000) / 58;
  Serial.println(d);
  delay(100);
}

Gotchas you'll hit

  • Use a 25ms timeout on pulseIn() — without it your loop blocks forever if nothing's in range.
  • Don't read faster than 10Hz; echoes from one ping can pollute the next.
  • Soft surfaces (curtains, sofa cushions) absorb ultrasound and give zero reading.
  • At very close range (<3cm) the sensor's own ringing fools the detector. Bonus exercise: use the JSN-SR04T waterproof variant if you need outdoor use.