The ultrasonic distance sensor HC-SR04 measures proximity by emitting a 40kHz acoustic burst and timing the returning echo. The direct answer for integration: it outputs a strict 5V digital TTL pulse on its Echo pin, where the pulse width in microseconds corresponds directly to the round-trip time of the sound wave. It does not output an analog voltage or a current loop. To use it with 3.3V microcontrollers like the ESP32 or Raspberry Pi, you must step down the Echo signal to prevent GPIO damage.

Sensing Principle and Core Specifications

The HC-SR04 measures distance using time-of-flight (ToF) acoustics. When triggered, the transmitter transducer fires a burst of eight 40kHz ultrasonic pulses and the internal flip-flop sets the Echo pin HIGH. The receiver transducer then listens for the reflected sound wave. Once the echo is detected, the Echo pin drops LOW. By measuring the time elapsed between the trigger pulse and the falling edge of the echo, the microcontroller calculates the distance based on the speed of sound in air.

Because the sound wave travels to the target and back, the measured time must be divided by two to find the actual one-way distance. The speed of sound is roughly 343 meters per second at 20°C (68°F), meaning sound travels approximately 1 centimeter every 29.15 microseconds, or 1 inch every 74.0 microseconds. This physical constant forms the basis of the raw-to-unit scaling math used in your firmware.

HC-SR04 Specification Sheet (Real-World Bench Values)
Parameter Value Bench Notes & Constraints
Operating Voltage 5V DC (4.8V – 5.5V) Will not reliably trigger on 3.3V. Do not power directly from ESP32 3V3 pin.
Quiescent Current < 2mA Idle state between measurements.
Working Current 15mA (peak) Drawn during the 40kHz burst transmission phase.
Ranging Distance 2cm to 400cm Blind zone is < 2cm due to transmitter ringing decay time.
Resolution 0.3cm (theoretical) Limited by the 8.5mm wavelength of 40kHz sound in air.
Trigger Input 10µs TTL HIGH Minimum pulse width required to initiate the measurement cycle.
Echo Output Proportional 5V TTL Stays HIGH for up to ~24ms if no echo is received (timeout).
Beam Angle < 15° cone Effective detection cone; wider for large, flat targets.

Wiring, Pinout, and Output Signal Mechanics

Understanding what the output actually is prevents the most common beginner mistake: frying a 3.3V microcontroller. The Echo pin is a digital push-pull output that swings from 0V to VCC (5V). It is not an analog signal that varies in amplitude based on distance; the amplitude is always 5V, and only the duration of the HIGH state changes. Because the ESP32 and Raspberry Pi Pico GPIO pins are strictly 3.3V tolerant, feeding a 5V Echo signal directly into them will degrade or destroy the silicon over time.

HC-SR04 Wiring and Pinout Table
Sensor Pin Function Supply Range / Logic ESP32 / 3.3V MCU Connection
VCC Power Input 4.8V – 5.5V DC Connect to 5V pin (e.g., ESP32 VIN or USB 5V).
Trig Trigger Input 5V Tolerant Digital Connect directly to any ESP32 GPIO (3.3V HIGH is sufficient to trigger).
Echo Echo Output 5V Digital TTL Must use a voltage divider to step 5V down to ~3.3V.
GND Ground 0V Reference Connect to MCU GND. Must share a common ground plane.
Callout Tip: The Voltage Divider Math
To step the 5V Echo pin down to a safe 3.3V, use a simple resistor divider. Connect a 1kΩ resistor (R1) in series with the Echo pin, and a 2kΩ resistor (R2) from the junction to GND. The formula is Vout = Vin * (R2 / (R1 + R2)). 5V * (2000 / 3000) = 3.33V. This safely interfaces the sensor with any 3.3V logic board.

Raw-to-Unit Math and Microcontroller Code

To convert the raw microsecond pulse width into physical units, we rely on the speed of sound in dry air at 20°C, which is 343 m/s. This translates to 0.0343 cm/µs. Since the sound travels to the object and back, we divide the speed by two (0.01715 cm/µs). Taking the reciprocal gives us the divisor for the round-trip time:

  • Distance (cm) = Pulse_Width_µs / 58.3
  • Distance (inches) = Pulse_Width_µs / 148.0

Below is a robust ESP32/Arduino C++ implementation. A critical E-E-A-T note for bench work: the Arduino pulseIn() function will block execution indefinitely if no echo is returned. You must always use the three-argument version with a timeout (e.g., 30000µs) to prevent your main loop from freezing when the sensor stares into an open void or absorbs into soft foam.

// HC-SR04 ESP32 Interfacing Code with Timeout Protection
const int trigPin = 5;
const int echoPin = 18; // Connect via 1k/2k voltage divider

void setup() {
  Serial.begin(115200);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  long duration;
  float distance_cm;

  // 1. Clear the trigger pin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  // 2. Send 10µs trigger pulse
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // 3. Read echo with 30ms timeout (prevents infinite lockup)
  duration = pulseIn(echoPin, HIGH, 30000);

  // 4. Raw-to-Unit Math
  if (duration == 0) {
    Serial.println("Error: Timeout / No Echo Received");
  } else {
    distance_cm = duration / 58.3;
    Serial.print("Distance: ");
    Serial.print(distance_cm);
    Serial.println(" cm");
  }

  delay(60); // Wait 60ms between pings to avoid acoustic crosstalk
}

Calibration and Scaling: The 58.3 divisor assumes 20°C. If your project operates in a freezer or a hot attic, the speed of sound changes by roughly 0.6 m/s for every 1°C change. For high-precision industrial applications, add a DS18B20 temperature sensor and dynamically calculate the divisor: divisor = (331.4 + (0.6 * temp_C)) / 10000 * 2. For hobbyist room-temperature projects, the static 58.3 divisor is perfectly adequate.

Real-World Interference, Calibration, and Edge Cases

The HC-SR04 is notoriously susceptible to environmental and electrical interference. Understanding these failure modes separates a working prototype from a reliable installation.

  1. Acoustic Crosstalk: If you mount multiple HC-SR04 sensors facing the same area (e.g., a robot car), Sensor A will trigger Sensor B's receiver, resulting in wildly inaccurate short readings. Fix: Fire the sensors sequentially in software with a 60ms delay between each, or physically angle them away from each other.
  2. Soft and Angled Targets: The 40kHz wave reflects poorly off acoustic foam, heavy curtains, or targets angled greater than 15° away from the sensor's normal vector. The sound scatters, the receiver hears nothing, and pulseIn times out. Fix: Use a physical target flag if measuring soft materials.
  3. Power Supply Noise: The internal oscillator is sensitive to VCC ripple. Cheap 5V buck converters from USB ports often introduce high-frequency noise that causes the Echo pulse width to jitter by ±2cm. Fix: Place a 100µF electrolytic capacitor and a 0.1µF ceramic capacitor across the VCC and GND pins directly at the sensor header.
  4. The 'Lockup' Bug: On many cheap clone boards, if the sensor is powered on while the Echo pin is already receiving an echo, or if it misses an echo entirely, the internal MAX232-equivalent chip can lock the Echo pin HIGH permanently until a physical power cycle occurs. Fix: If building a remote, unattended node, power the HC-SR04 VCC through a GPIO-controlled MOSFET so the ESP32 can hard-reset the sensor's power if it detects consecutive timeouts.
Alternative Sensor Comparison: When to Upgrade
Sensor Model Interface Logic Level Best Use Case
HC-SR04 Analog ToF (Pulse) 5V (Needs Divider) Indoor hobby projects, dry environments, basic robotics.
JSN-SR04T Analog ToF (Pulse) 5V (Needs Divider) Outdoor applications, sump pumps, waterproof environments (IP67 transducer).
RCWL-1601 I2C / UART / PWM 3.3V Native Direct ESP32/Pi Pico wiring (no divider), high-noise environments, multi-sensor I2C buses.

By respecting the 5V logic requirements, implementing the raw-to-unit math with proper timeout guards, and filtering out acoustic crosstalk, the HC-SR04 remains one of the most cost-effective and reliable distance sensors on the workbench.