How-To Guide Beginner 12 دقيقة

HC-SR04 Ultrasonic Distance Sensor: Arduino & ESP32 Wiring, Math & Troubleshooting

Complete guide to the HC-SR04 ultrasonic sensor. Learn distance calculation math, non-blocking code, and safe 3.3V ESP32 voltage divider wiring.

Verified by MOKWN Hardware Engineering Team
HC-SR04 Ultrasonic Distance Sensor: Arduino & ESP32 Wiring, Math & Troubleshooting
Required Components (BOM)

Project Components Available in Egypt

All components tested and genuine with fast nationwide delivery in Egypt

Add All to Cart
Ultrasonic Sensor Module
Qty: 1
Ultrasonic Sensor Module
حساس قياس المسافة بدقة من 2 سم حتى 400 سم
Ultrasonic Sensor Mount (Compatible with Servo)
Qty: 1
Ultrasonic Sensor Mount (Compatible with Servo)
حامل ميكانيكي لتثبيت الحساس على سيرفو موتور لتفادي العوائق
SG90 Micro Servo Motor (180°, 1.6kg·cm, Plastic Gears)
Qty: 1
SG90 Micro Servo Motor (180°, 1.6kg·cm, Plastic Gears)
موتور سيرفو لتحريك الحساس يميناً ويساراً في الروبوتات

Introduction: Ultrasonic Vision for Autonomous Robots

The HC-SR04 ultrasonic distance sensor provides robots and automated guided vehicles (AGVs) with reliable non-contact distance measurement from 2 cm to 400 cm.

Operating at 40 kHz, it mimics bat echolocation by emitting high-frequency acoustic bursts and measuring the travel time of the returned echo.

---

Pinout Configuration

  1. VCC: 5V DC Supply.
  2. TRIG (Trigger): Input pin; receives a 10µs HIGH pulse from the MCU to initiate sound transmission.
  3. ECHO: Output pin; stays HIGH for the exact duration of the round-trip acoustic transit.
  4. GND: Ground reference.

---

Mathematical Derivation

Speed of sound in dry air at 20°C is approximately 343 m/s (0.0343 cm/µs). Because the sonic pulse travels to the object and bounces back, the actual physical distance is half the total traveled distance:

$\text{Distance (cm)} = \frac{\text{Duration (\mu s)} \times 0.0343}{2}$

---

Clean Arduino C++ Implementation

const int trigPin = 9;
const int echoPin = 10;

void setup() {
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.println("HC-SR04 Initialized.");
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  long duration = pulseIn(echoPin, HIGH, 30000); // 30ms timeout

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

  delay(100);
}

---

Crucial 3.3V MCU Protection (ESP32 / Raspberry Pi Pico)

Because the Echo output transmits at 5V, connecting it directly to a 3.3V microcontroller will degrade or blow the input pin buffer.

Safe Two-Resistor Divider:

  • Connect Echo through a 1kΩ resistor to the MCU pin.
  • Connect a 2kΩ resistor from the MCU pin to GND.
  • Formula: $V_{out} = 5V \times \frac{2k}{1k + 2k} = 3.33V$ (safe and clean).

Frequently Asked Questions

How does the HC-SR04 calculate distance in centimeters?

The formula is: Distance (cm) = (Duration in microseconds * 0.0343) / 2. Here, 0.0343 cm/µs is the speed of sound, divided by 2 because the wave travels to the obstacle and bounces back.

Why can the HC-SR04 damage an ESP32 GPIO pin?

The HC-SR04 operates at 5V and its Echo pin outputs a 5V signal. Connecting this directly to a 3.3V ESP32 GPIO can destroy the pin. Always use a voltage divider (1kΩ and 2kΩ) on the Echo line.

What is the effective measurement range and beam angle?

The HC-SR04 measures between 2 cm and 400 cm with a theoretical accuracy of 3 mm, across an effective 15-degree cone angle. Soft, angled, or sound-absorbing surfaces may reflect waves away.

Ask Volt AI Hardware Assistant

Need help debugging your circuit wiring or verifying your code? Chat with Volt directly.

Start Chat with Volt