MyRoboPathOpen Robotics Lab
Arduino Uno #7 of 35
Est. 0.75 Hours
Budget: $3 - $5
Beginner

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.

Arduino Uno R3HC-SR04 UltrasonicTime-of-Flight MathpulseIn() TimeoutProximity Alert
HC-SR04 Ultrasonic Sonar Distance Sensor Blueprint
HC-SR04 Ultrasonic Sonar Distance SensorCAD Blueprint

Key Learning Objectives & Robotics Concepts

By building and programming this project, you will master the following core engineering skills:

1Derive distance from round-trip acoustic Time-of-Flight: d(cm) = (duration_µs × 0.0343) / 2.
2Trigger the HC-SR04 cleanly with a 2µs LOW settle followed by a precise 10µs HIGH pulse.
3Use pulseIn() timeout arguments to prevent firmware freezes when no echo returns.
4Apply a 3-sample median filter to eliminate stray acoustic reflections.

Power Architecture & Voltage Staging

5V / 3.3V Regulated Power

The 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.

HC-SR04 Ultrasonic Sonar Distance Sensor Power Architecture Schematic
Figure: Regulated Arduino Uno supply rails, current budget, and component protection.Power Schematic

Bill of Materials (BOM) & Hardware Components

Bill of Materials for HC-SR04 Ultrasonic Sonar Distance Sensor
ComponentSpecifications & AlternativeQtyApprox Cost
Arduino Uno R3ATmega328P @ 16MHz1$8.00
HC-SR04 Ultrasonic Sensor2cm–400cm range, 15° beam cone, 40kHz1$2.00
5mm Red LED + 220Ω ResistorClose-range proximity alert indicator1$0.15
Breadboard & Jumper WiresMale-to-Male or Male-to-Female leads1$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.

Figure: Complete Arduino Uno R3 pin-to-pin wiring schematic for HC-SR04 Ultrasonic Sonar Distance Sensor.
Figure: Complete Arduino Uno R3 pin-to-pin wiring schematic for HC-SR04 Ultrasonic Sonar Distance Sensor.Wiring Schematic

Autonomous Behavior & Finite State Machine (FSM)

Deterministic Arduino loop handling HC-SR04 40kHz Ultrasonic Transducer acquisition, filtering, and real-time output updates.

Figure: Firmware execution flow and state transitions for HC-SR04 Ultrasonic Sonar Distance Sensor.
Figure: Firmware execution flow and state transitions for HC-SR04 Ultrasonic Sonar Distance Sensor.Control Algorithm

Step-by-Step Physical Assembly & Wiring Tutorial

Follow each of the 5 sequential milestone stages with technical photos, wiring checks, and pre-flight tests.

1

Inspect HC-SR04 Transducer Orientation

Duration: 5 Mins

Mount the sensor upright on the breadboard edge so its twin aluminum barrels face an unobstructed path.

HC-SR04 Ultrasonic Sonar Distance Sensor hardware layout diagram
Stage 1: HC-SR04 40kHz Ultrasonic Transducer hardware inspection & pinout overview.Stage 1 Diagram
Step Action Checklist:
  • 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.
Engineering & Tuning Tip: Soft fabric or steeply angled walls deflect 40kHz sound away; test first with a flat notebook or box.
2

Wire Sensor & Proximity Alert LED

Duration: 10 Mins

Connect VCC/GND, TRIG to D9, ECHO to D10, and the warning LED to D6.

HC-SR04 Ultrasonic Sonar Distance Sensor breadboard wiring check diagram
Stage 2: Breadboard layout & Arduino Uno pin-to-pin wiring audit.Stage 2 Diagram
Step Action Checklist:
  • Wire HC-SR04 VCC → 5V and GND → GND.
  • Wire TRIG → D9 and ECHO → D10.
  • Wire D6 → 220Ω resistor → Red LED anode → cathode to GND.
Engineering & Tuning Tip: Double-check TRIG vs ECHO—swapping them yields constant 0cm readings.
3

Verify Supply Voltage & Clear Beam Cone

Duration: 5 Mins

Ensure the sensor receives full 5V (running HC-SR04 on 3.3V severely degrades echo range).

HC-SR04 Ultrasonic Sonar Distance Sensor power rail protection diagram
Stage 3: Supply rail check (USB 5.0V Regulated Rail (≈15mA active)) and circuit protection verification.Stage 3 Diagram
Step Action Checklist:
  • Verify VCC jumper sits firmly in Arduino 5V (not 3.3V).
  • Aim the sensor toward a flat target 20cm away.
  • Plug in USB power.
Engineering & Tuning Tip: Keep at least 60ms between successive sonar pings so echoes from distant walls die out first.
4

Upload Median-Filtered Rangefinder Sketch

Duration: 10 Mins

Flash the sonar code and verify centimeter accuracy against a ruler.

HC-SR04 Ultrasonic Sonar Distance Sensor serial telemetry verification diagram
Stage 4: Firmware upload & 115200 baud Serial Monitor verification.Stage 4 Diagram
Step Action Checklist:
  • 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.
Engineering & Tuning Tip: Speed of sound varies slightly with room temperature: v ≈ 331.3 + 0.606 × T(°C) m/s.
5

Test Proximity Alert Threshold

Duration: 5 Mins

Move your hand inside 15cm to trigger the red warning LED cleanly.

HC-SR04 Ultrasonic Sonar Distance Sensor live operational logic diagram
Stage 5: Live operational logic flow & calibration verification.Stage 5 Diagram
Step Action Checklist:
  • 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.
Engineering & Tuning Tip: Below 2cm the transmitter rings directly into the receiver—treat <2.5cm as minimum blind zone.

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 Diagnostic

Minimal standalone sketch to verify pin wiring and signal response for HC-SR04 40kHz Ultrasonic Transducer before running the full project firmware.

Arduino IDE Diagnostic ScriptC++ / Arduino
// 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);
}
Expected Output: Echo us: 1166 | cm: 20.0 when aimed at a flat target 20cm away.

Complete Production Firmware

Full working C++ source code with pin mappings, non-blocking timers, and FSM avoidance routines.

arduino_uno_hcsr04_ultrasonic_rangefinder.ino
arduino_uno_hcsr04_ultrasonic_rangefinder.inoArduino C++
/**
 * 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

1Double-check all 5 Arduino Uno pin connections against the wiring schematic before plugging in USB.
2Upload the Bench Diagnostic sketch first and confirm Serial Monitor at 115200 baud matches: Echo us: 1166 | cm: 20.0 when aimed at a flat target 20cm away.
3Upload the complete production sketch and verify every condition in the operational truth table below.

Input Signal vs. System Output Truth Table:

Operational truth table for HC-SR04 Ultrasonic Sonar Distance Sensor
Input / StatePin / SignalDetected ConditionExpected Output
2.0 – 15.0 cmEcho 116–875µsClose Obstacle DetectedD6 LED ON + Alert Log
15.1 – 400 cmEcho 880–23300µsSafe ClearanceD6 LED OFF + Print cm
Timeout (0µs)> 30,000µsNo Reflective TargetReport OUT OF RANGE

Engineering Troubleshooting Matrix

Engineering troubleshooting matrix for HC-SR04 Ultrasonic Sonar Distance Sensor
ProblemLikely CauseDiagnostic CheckEngineering Solution
Always prints OUT OF RANGE or 0.0 cmTRIG and ECHO wires swapped or powered from 3.3VVerify D9→TRIG, D10→ECHO, and 5V→VCCCorrect pin mapping and ensure solid 5V supply.
Readings jump wildly between 5cm and 200cmPing rate too fast (reverberation echoes) or angled targetTest with flat book perpendicular to sensorKeep ≥35–60ms between pings and use median filtering.
Accurate at 20cm but wrong by 5% in cold/hot roomSpeed of sound shifts with air temperatureCompare against ruler at room tempPair 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:

Level 1Temperature-Compensated Sonar

Feed live DHT11 temperature into c = 331.3 + 0.606 * T for millimeter-grade calibration.

Level 2Garage Parking Traffic Light

Use Green (>40cm), Yellow (15–40cm), and Red (<15cm) LEDs plus a piezo buzzer.

Level 3OLED Live Distance Bar

Display real-time distance and a horizontal proximity bar on the Project 4 OLED.