HC-SR04 Ultrasonic Sonar Distance Sensor
Measure non-contact distances from 2cm to 400cm using 40kHz acoustic Time-of-Flight echoes and median filtering.
Build an accurate ultrasonic sonar rangefinder with the HC-SR04 module. Learn how a 10µs trigger burst launches eight 40kHz sound pulses, measure round-trip echo duration with pulseIn(), convert microseconds into centimeters using the speed of sound, and filter noisy echoes.
Key Learning Objectives & Robotics Concepts
By building and programming this project, you will master the following core engineering skills:
Power Architecture & Voltage Staging
5V / 3.3V Regulated PowerThe HC-SR04 requires a clean 5.0V supply (drawing ~15mA during burst transmission) and outputs 5V TTL logic directly compatible with Arduino Uno digital inputs. Timeout cap of 30,000µs prevents pulseIn() lockups; minimum 60ms between pings avoids ghost echoes.
Bill of Materials (BOM) & Hardware Components
| Component | Specifications & Alternative | Qty | Approx Cost |
|---|---|---|---|
| Arduino Uno R3 | ATmega328P @ 16MHz | 1 | $8.00 |
| HC-SR04 Ultrasonic Sensor | 2cm–400cm range, 15° beam cone, 40kHz | 1 | $2.00 |
| 5mm Red LED + 220Ω Resistor | Close-range proximity alert indicator | 1 | $0.15 |
| Breadboard & Jumper Wires | Male-to-Male or Male-to-Female leads | 1 | $2.00 |
Electrical & System Architecture
Wire HC-SR04 VCC to 5V, GND to GND, TRIG to D9, ECHO to D10, and an optional proximity alert LED (with 220Ω resistor) to D6.
Autonomous Behavior & Finite State Machine (FSM)
Deterministic Arduino loop handling HC-SR04 40kHz Ultrasonic Transducer acquisition, filtering, and real-time output updates.
Step-by-Step Physical Assembly & Wiring Tutorial
Follow each of the 5 sequential milestone stages with technical photos, wiring checks, and pre-flight tests.
Inspect HC-SR04 Transducer Orientation
Mount the sensor upright on the breadboard edge so its twin aluminum barrels face an unobstructed path.
- Seat the 4-pin HC-SR04 header along the front edge of the breadboard.
- Confirm pin labels from left to right: VCC, TRIG, ECHO, GND.
- Clear loose jumper wires from directly in front of the transducers.
Wire Sensor & Proximity Alert LED
Connect VCC/GND, TRIG to D9, ECHO to D10, and the warning LED to D6.
- Wire HC-SR04 VCC → 5V and GND → GND.
- Wire TRIG → D9 and ECHO → D10.
- Wire D6 → 220Ω resistor → Red LED anode → cathode to GND.
Verify Supply Voltage & Clear Beam Cone
Ensure the sensor receives full 5V (running HC-SR04 on 3.3V severely degrades echo range).
- Verify VCC jumper sits firmly in Arduino 5V (not 3.3V).
- Aim the sensor toward a flat target 20cm away.
- Plug in USB power.
Upload Median-Filtered Rangefinder Sketch
Flash the sonar code and verify centimeter accuracy against a ruler.
- Upload the production sketch below.
- Open Serial Monitor at 115200 baud.
- Hold a flat book at 10cm, 20cm, and 30cm and verify readings match within ±0.5cm.
Test Proximity Alert Threshold
Move your hand inside 15cm to trigger the red warning LED cleanly.
- Bring a flat target closer than 15cm and confirm D6 LED turns ON.
- Pull target back beyond 15cm and confirm LED turns OFF.
- Observe out-of-range timeout handling when aimed at open space.
Subsystem Benchtop Verification Scripts
Test each hardware subsystem independently before deploying the full autonomous firmware.
1Bench Diagnostic: HC-SR04 40kHz Ultrasonic Transducer Hardware Check
Subsystem DiagnosticMinimal standalone sketch to verify pin wiring and signal response for HC-SR04 40kHz Ultrasonic Transducer before running the full project firmware.
// Diagnostic: Single-Shot HC-SR04 Echo Duration (µs)
const uint8_t TRIG = 9, ECHO = 10;
void setup() { pinMode(TRIG, OUTPUT); pinMode(ECHO, INPUT); Serial.begin(115200); }
void loop() {
digitalWrite(TRIG, LOW); delayMicroseconds(2);
digitalWrite(TRIG, HIGH); delayMicroseconds(10); digitalWrite(TRIG, LOW);
unsigned long us = pulseIn(ECHO, HIGH, 30000UL);
Serial.print("Echo us: "); Serial.print(us); Serial.print(" | cm: "); Serial.println(us * 0.0343 / 2.0, 1);
delay(150);
}Complete Production Firmware
Full working C++ source code with pin mappings, non-blocking timers, and FSM avoidance routines.
/**
* Project 7: HC-SR04 Ultrasonic Rangefinder with Median Filter
* Board: Arduino Uno R3 | Pins: D9 (TRIG), D10 (ECHO), D6 (Alert LED)
*/
const uint8_t TRIG_PIN = 9;
const uint8_t ECHO_PIN = 10;
const uint8_t ALERT_LED = 6;
const float ALERT_THRESHOLD_CM = 15.0;
float pingOnceCm() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
unsigned long duration = pulseIn(ECHO_PIN, HIGH, 30000UL);
if (duration == 0) return -1.0; // Timeout / out of range
return (duration * 0.0343f) * 0.5f;
}
float medianOfThree(float a, float b, float c) {
if ((a <= b && b <= c) || (c <= b && b <= a)) return b;
if ((b <= a && a <= c) || (c <= a && a <= b)) return a;
return c;
}
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(ALERT_LED, OUTPUT);
Serial.begin(115200);
Serial.println(F("HC-SR04 Sonar Rangefinder Ready"));
}
void loop() {
float s1 = pingOnceCm(); delay(35);
float s2 = pingOnceCm(); delay(35);
float s3 = pingOnceCm(); delay(35);
float distCm = medianOfThree(s1, s2, s3);
if (distCm < 0) {
digitalWrite(ALERT_LED, LOW);
Serial.println(F("Target: OUT OF RANGE (>400 cm)"));
} else {
bool alert = (distCm <= ALERT_THRESHOLD_CM);
digitalWrite(ALERT_LED, alert ? HIGH : LOW);
Serial.print(F("Distance: "));
Serial.print(distCm, 1);
Serial.print(F(" cm ("));
Serial.print(distCm / 2.54f, 1);
Serial.print(F(" in) | Status: "));
Serial.println(alert ? F("PROXIMITY ALERT") : F("CLEAR"));
}
delay(120);
}Firmware Architecture Explanation:
- Uses a 30,000µs pulseIn() timeout (~5.1m max) so lost echoes never hang the loop for a full second.
- Computes a 3-sample median filter to reject single-ping acoustic spikes without lagging real movement.
- Drives a hardware warning LED on D6 whenever distance drops to or below 15.0cm.
Operational Verification & Pin State Matrix
Input Signal vs. System Output Truth Table:
| Input / State | Pin / Signal | Detected Condition | Expected Output |
|---|---|---|---|
| 2.0 – 15.0 cm | Echo 116–875µs | Close Obstacle Detected | D6 LED ON + Alert Log |
| 15.1 – 400 cm | Echo 880–23300µs | Safe Clearance | D6 LED OFF + Print cm |
| Timeout (0µs) | > 30,000µs | No Reflective Target | Report OUT OF RANGE |
Engineering Troubleshooting Matrix
| Problem | Likely Cause | Diagnostic Check | Engineering Solution |
|---|---|---|---|
| Always prints OUT OF RANGE or 0.0 cm | TRIG and ECHO wires swapped or powered from 3.3V | Verify D9→TRIG, D10→ECHO, and 5V→VCC | Correct pin mapping and ensure solid 5V supply. |
| Readings jump wildly between 5cm and 200cm | Ping rate too fast (reverberation echoes) or angled target | Test with flat book perpendicular to sensor | Keep ≥35–60ms between pings and use median filtering. |
| Accurate at 20cm but wrong by 5% in cold/hot room | Speed of sound shifts with air temperature | Compare against ruler at room temp | Pair with DHT11 (Project 3) to temperature-compensate speed of sound. |
Engineering Challenges & Upgrades
Take your build to the next level with these progressive engineering upgrades:
Feed live DHT11 temperature into c = 331.3 + 0.606 * T for millimeter-grade calibration.
Use Green (>40cm), Yellow (15–40cm), and Red (<15cm) LEDs plus a piezo buzzer.
Display real-time distance and a horizontal proximity bar on the Project 4 OLED.