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
- VCC: 5V DC Supply.
- TRIG (Trigger): Input pin; receives a 10µs HIGH pulse from the MCU to initiate sound transmission.
- ECHO: Output pin; stays HIGH for the exact duration of the round-trip acoustic transit.
- 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).