ToolSphere
Back to all articles
electronics

HC-SR04 Arduino Nano Perfboard Guide

2026-11-128 min read

Try it: free PerfBoard & Stripboard Simulator

Plan perfboard or stripboard layouts and check connections

Open →

Breadboard prototypes are great for testing concepts on your workbench, but loose jumper wires make them fragile in robotics, automated carts, or workshop proximity alarms. Moving your circuit onto an isolated-pad perfboard transforms loose breadboard wiring into a sturdy, permanent build that tolerates vibration and repeated handling.

This guide walks through building the schematic-verified Arduino Nano + HC-SR04 ultrasonic rangefinder and passive piezo buzzer circuit from ToolSphere's perfboard layout library. You will find the complete bill of materials, exact point-to-point pin wiring, the acoustic physics and distance formulas behind ultrasonic echo timing, three step-by-step worked examples, and a robust Arduino sketch with proper timeout handling.


Parts List from the Verified Layout

Every component in this build is matched to the nano-hcsr04-buzzer design in the perfboard simulator. Do not swap parts arbitrarily; the circuit is designed around a 5 V logic controller and a capacitive passive piezo element.

Quantity Component Designation Purpose & Specifications
1 Arduino Nano (ATmega328P) A1 Classic 5 V microcontroller module with two 15-pin female socket headers
1 HC-SR04 ultrasonic sensor J2 5 V ultrasonic transceiver module with a 4-conductor ribbon cable
1 Passive piezo transducer J3 Capacitive passive buzzer element (requires AC square wave tone)
1 1 kΩ resistor (1/4 W) R1 Series feed resistor from D5 to piezo (limits current to 5 mA)
1 10 kΩ resistor (1/4 W) R2 Parallel discharge resistor across piezo terminals
1 100 nF ceramic capacitor C1 High-frequency decoupling capacitor (labeled "104") across 5 V and GND
1 10 µF electrolytic capacitor C2 Bulk filtering capacitor (10 V or higher rating, polarized)
2 2-pin male/female headers J1, J3 J1 for regulated 5 V external power input; J3 for piezo leads
1 4-pin male/female header J2 Connection header for the HC-SR04 sensor cable
1 Regulated 5 V DC power supply External Clean 5 V bench supply or regulated wall adapter
1 Prototyping perfboard Base Standard single-sided perfboard with isolated 0.1-inch (2.54 mm) pads
- Solid-core hookup wire Jumpers 22 AWG or 24 AWG insulated copper wire and solder

Circuit Architecture & Pin Planning

Before heating your soldering iron, review your pin choices in the Arduino pin planner to ensure there are no timer conflicts or overcurrent conditions.

       +5V INPUT (J1)
       [+] --------+------------------+----------+--------- A1 Pin 27 (5V)
                   |                  |          |
                  === C2 (10 µF)     === C1     [1] VCC
                   |  (bulk)          |  (100n) [2] TRIG --- A1 Pin 5 (D2)
       [-] --------+------------------+         [3] ECHO --- A1 Pin 6 (D3)
                   |                            [4] GND  --- GND Bus
                  GND                           HC-SR04 (J2)

       A1 Pin 8 (D5) ----[ R1: 1 kΩ ]----+----- [+] J3 (Piezo +)
                                         |
                                       [ R2 ] 10 kΩ
                                         |
                                        GND ---- [-] J3 (Piezo -)

Arduino Nano (A1) Pin Allocations

  • D2 (Pin 5) → J2 Pin 2 (TRIG): Configured as a digital output. Emits a clean 10-microsecond trigger pulse that initiates the sensor burst.
  • D3 (Pin 6) → J2 Pin 3 (ECHO): Configured as a digital input. Measures the return pulse width emitted by the HC-SR04. On the ATmega328P, D3 is also external interrupt pin INT1, enabling optional non-blocking pulse timing.
  • D5 (Pin 8) → R1 (1 kΩ) → J3 Pin 1 (Piezo +): Configured as an audio output driven by the Arduino tone() function. Pin D5 connects to Timer0B or Timer2 depending on the core version, avoiding conflicts with basic system timing.
  • 5V (Pin 27) & GND (Pins 4, 29): Connects to the regulated 5 V rail and ground bus.

Piezo Drive Network: Why R1 and R2 Matter

A passive piezo transducer is essentially a ceramic capacitor (typically 15 nF to 30 nF) sandwiched between metal electrodes. It does not contain an internal oscillator. Applying a steady DC voltage produces only a brief click as the ceramic dielectric flexes once. Generating an audible beep requires an alternating square wave, produced by toggling the output pin with tone(5, frequency).

Because the piezo behaves as a capacitor, driving it directly from an AVR output pin causes high capacitive inrush spikes whenever the pin switches state.

  1. Series Resistor R1 (1 kΩ): ToolSphere's Ohm's law calculation computes the feed-current bound for an ideal 5 V pin and zero-voltage load:
    I = V / R = 5 V / 1,000 Ω = 0.005 A = 5 mA
    This 5 mA maximum feed current is well within the ATmega328P's safe continuous rating of 20 mA per pin. It protects the microcontroller output stage while delivering plenty of acoustic volume for a desktop alert.
  2. Discharge Resistor R2 (10 kΩ): Placed in parallel across J3, R2 provides an intentional path to drain residual charge from the ceramic element when the drive tone stops.
  3. No Flyback Diode Needed: Unlike electromagnetic buzzers, solenoids, or DC motors that contain inductive wire coils, a capacitive piezo does not generate large inductive flyback spikes when switched off. Hence, no reverse-biased diode is needed across J3.

Power & Decoupling

Ultrasonic bursts demand short spikes of current when the transmitter transducers fire. C1 (100 nF ceramic) filters high-frequency noise close to sensor header J2. C2 (10 µF electrolytic) supplies local bulk reservoir energy, preventing supply brownouts from glitching the Nano's reset pin.

[!WARNING]
Always disconnect external power at J1 before plugging in a USB cable to program the Nano. Do not feed 9 V or unregulated DC into the 5V terminal.


How the HC-SR04 Measures Distance

The HC-SR04 operates on the time-of-flight acoustic principle, similar to marine sonar and bat echolocation:

  1. The microcontroller holds TRIG LOW, then pulses it HIGH for at least 10 microseconds (10 µs).
  2. The HC-SR04's internal controller drives its 40 kHz ultrasonic transmitter with an 8-cycle burst.
  3. Simultaneously, the module sets its ECHO pin HIGH.
  4. The 40 kHz sound waves travel through the air, reflect off a target, and return to the receiver transducer.
  5. As soon as the receiver detects the reflected burst, the module pulls the ECHO pin LOW.
  6. The microcontroller measures the duration of the ECHO HIGH state in microseconds (t).
TRIG: ____|‾‾‾ 10 µs ‾‾‾|_________________________________________
           <-- 8-cycle 40 kHz sound wave travels out & returns -->
ECHO: ____________|‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ Round-Trip Time (t) ‾‾‾‾‾‾‾‾‾‾|___

The Acoustic Distance Formula

In dry air at room temperature (20 °C / 68 °F), the speed of sound is approximately:
v = 343 m/s = 34,300 cm/s = 0.0343 cm/µs

In US customary units:
v ≈ 1,125.3 ft/s = 13,504 in/s = 0.013504 in/µs
This equals approximately 1 inch for every 74.05 microseconds of travel.

Because the acoustic burst must travel forward to the object and bounce backward to the detector, the sound travels twice the one-way distance:
Total distance traveled = 2 × d = v × t

Solving for one-way distance:
d = (v × t) / 2

Expressed in centimeters:
d (cm) = (0.0343 cm/µs × t) / 2 = t / 58.3

Expressed in inches:
d (in) = d (cm) / 2.54 = t / 148.1


Worked Examples

Every numerical result below is calculated from the physical equations using ToolSphere's conversion and calculation libraries.

Worked Example 1: Calculating Distance from Echo Duration

Suppose the Arduino measures an echo pulse width of t = 1,000 µs (1.0 millisecond).

  1. Compute round-trip acoustic distance:
    Round-trip = 0.0343 cm/µs × 1,000 µs = 34.30 cm
  2. Divide by 2 for one-way distance:
    d = 34.30 cm / 2 = 17.15 cm
  3. Convert to US customary units:
    d = 17.15 cm / 2.54 cm/in = 6.75 inches

An echo duration of 1,000 µs indicates an obstacle positioned 6.75 inches (17.15 cm) away.

Worked Example 2: Target at 10.0 Inches

Suppose an automated vehicle stops whenever an obstacle is within 10.0 inches (25.40 cm). What echo duration will the Arduino detect at that threshold?

  1. Find the round-trip distance:
    Round-trip = 2 × 25.40 cm = 50.80 cm
  2. Solve for travel time at 0.0343 cm/µs:
    t = 50.80 cm / 0.0343 cm/µs = 1,481.05 µs ≈ 1,481 µs

When the target is at 10.0 inches, the ECHO pin remains HIGH for 1,481 µs.

Worked Example 3: Near-Field Obstacle at 4.0 Inches

For a close-range warning threshold of 4.0 inches (10.16 cm):

  1. Round-trip distance:
    Round-trip = 2 × 10.16 cm = 20.32 cm
  2. Expected pulse duration:
    t = 20.32 cm / 0.0343 cm/µs = 592.42 µs ≈ 592 µs

The microcontroller detects an echo pulse of 592 µs.


Step-by-Step Perfboard Assembly

Assemble your board methodically using isolated-pad perfboard. Follow this sequence to prevent accidental solder bridges and verify voltages safely.

+-------------------------------------------------------------+
| [J1: 5V IN]                  [J2: HC-SR04 CABLE HEADER]     |
|  Pin 1: +5V                   Pin 1: +5V (VCC)              |
|  Pin 2: GND                   Pin 2: D2  (TRIG)             |
|                               Pin 3: D3  (ECHO)             |
|                               Pin 4: GND (GND)              |
|   +-----------------------+                                 |
|   |   ARDUINO NANO (A1)   |        C1 (100nF)               |
|   |   (Female Sockets)    |        C2 (10µF bulk)           |
|   +-----------------------+                                 |
|                                                             |
|  [R1: 1kΩ] ------> [J3: PIEZO] <------ [R2: 10kΩ to GND]    |
|  (from D5)          Pin 1: (+)                              |
|                     Pin 2: (-)                              |
+-------------------------------------------------------------+

1. Sockets and Headers First

  • Solder two 15-pin female header strips spaced 0.6 inches (6 perfboard holes) apart to hold the Nano. Plugging the Nano into sockets allows you to remove it easily for reprogramming or reuse.
  • Solder 2-pin header J1 (external power) and 2-pin header J3 (piezo) near the board perimeter.
  • Solder 4-pin header J2 near the top edge for the ultrasonic sensor cable.

2. Ground and Power Rails

  • Create a common ground bus along an outer row using bare or insulated jumper wire. Connect Nano pin 4 and pin 29 to this common ground.
  • Run a 5 V power rail connecting J1 pin 1 to Nano pin 27 (5V) and J2 pin 1 (VCC).
  • Install C1 (100 nF ceramic) and C2 (10 µF electrolytic) directly across the 5 V and GND rails close to J2. Ensure C2's negative stripe connects to ground.

3. Sensor Signal Wiring

  • Run an insulated jumper wire from Nano pin 5 (D2) to J2 pin 2 (TRIG).
  • Run an insulated jumper wire from Nano pin 6 (D3) to J2 pin 3 (ECHO).
  • Connect J2 pin 4 to the common ground bus.

4. Buzzer Drive Network

  • Run a jumper from Nano pin 8 (D5) to one lead of resistor R1 (1 kΩ).
  • Connect the other lead of R1 to J3 pin 1 (Piezo +).
  • Solder resistor R2 (10 kΩ) directly across J3 pins 1 and 2.
  • Connect J3 pin 2 to the common ground bus.

Pre-Power Testing Checklist

Never insert your Arduino Nano into a newly soldered board without checking continuity first.

  1. Check for Power Shorts: With the Nano removed and power disconnected, place a digital multimeter in continuity mode across J1 pins 1 and 2. It must not beep. A continuous tone indicates a solder bridge between 5 V and ground.
  2. Verify Header Voltages: Connect your regulated 5 V supply to J1. Use a multimeter to measure the voltage at the socket pins:
    • Verify +5.0 V between socket pin 27 (5V) and socket pin 4 (GND).
    • Verify +5.0 V between J2 pin 1 and J2 pin 4.
    • Verify 0.0 V across all digital signal socket pads (D2, D3, D5).
  3. Power Down Before Insertion: Turn off the power supply, insert the Arduino Nano into its socket rows with its USB mini-connector facing the board edge, and connect the HC-SR04 cable to J2.

Minimal Arduino Sketch

This complete, production-ready Arduino sketch triggers the HC-SR04, measures distance in inches and centimeters, handles echo timeouts gracefully, and sounds a proximity chirp when an object is closer than 6.0 inches (15.2 cm).

/*
 * Arduino Nano + HC-SR04 Ultrasonic Distance Sensor & Piezo Alarm
 * Verified for ToolSphere perfboard layout: nano-hcsr04-buzzer
 */

const int TRIG_PIN   = 2;  // Digital Pin 2 -> HC-SR04 TRIG
const int ECHO_PIN   = 3;  // Digital Pin 3 -> HC-SR04 ECHO
const int BUZZER_PIN = 5;  // Digital Pin 5 -> 1 kΩ -> Piezo (+)

// Proximity alert threshold in inches
const float ALARM_DISTANCE_INCHES = 6.0;

// Maximum sensor timeout: 30,000 µs corresponds to ~16 feet (5 meters)
const unsigned long ECHO_TIMEOUT_US = 30000;

void setup() {
  Serial.begin(9600);
  
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  pinMode(BUZZER_PIN, OUTPUT);
  
  // Ensure trigger pin begins LOW
  digitalWrite(TRIG_PIN, LOW);
  noTone(BUZZER_PIN);
  
  delay(100);
  Serial.println(F("HC-SR04 Distance Sensor Initialized"));
}

void loop() {
  // 1. Send clean 10-microsecond trigger pulse
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  
  // 2. Measure ECHO pulse duration in microseconds
  unsigned long duration = pulseIn(ECHO_PIN, HIGH, ECHO_TIMEOUT_US);
  
  // 3. Handle measurement result
  if (duration == 0) {
    // Timeout: no return echo received (out of range or absorbed)
    noTone(BUZZER_PIN);
    Serial.println(F("Status: No echo detected (out of range)"));
  } else {
    // Calculate one-way distance using speed of sound (0.0343 cm/µs)
    float distanceCm = (duration * 0.0343) / 2.0;
    float distanceIn = distanceCm / 2.54;
    
    Serial.print(F("Distance: "));
    Serial.print(distanceIn, 2);
    Serial.print(F(" in ("));
    Serial.print(distanceCm, 1);
    Serial.println(F(" cm)"));
    
    // 4. Proximity alarm logic
    if (distanceIn <= ALARM_DISTANCE_INCHES && distanceIn > 0.5) {
      // Sound a 2.5 kHz alert chirp for 40 ms
      tone(BUZZER_PIN, 2500, 40);
    } else {
      noTone(BUZZER_PIN);
    }
  }
  
  // 5. Allow at least 60 ms between pings to prevent echo overlap
  delay(60);
}

Frequently Asked Questions

Which Arduino boards work with this layout?

This layout is specifically designed for the classic ATmega328P 5 V Arduino Nano. Do not substitute a 3.3 V development board such as the Nano ESP32, Nano Every, or Raspberry Pi Pico without adding bidirectional logic level shifters on the 5 V ECHO line.

What does an echo duration of zero mean?

A zero reading from pulseIn() indicates a timeout: the sensor sent a ping, but no reflected acoustic wave reached the receiver within the specified time window. In software, always treat duration zero as an invalid or out-of-range state, never as zero inches. Treating timeouts as zero distance causes proximity alarms to sound continuously whenever targets move out of range.

Can I substitute an active buzzer for the passive piezo?

No. An active buzzer contains an internal oscillator circuit and is designed to sound whenever a continuous DC voltage is applied. This layout uses a capacitive passive piezo transducer driven by Arduino's tone() library through current-limiting and discharge resistors. Connecting an active buzzer through a 1 kΩ series resistor may prevent it from drawing sufficient operating current.

What is the purpose of the 10 kΩ resistor (R2) across the buzzer?

A passive piezo transducer is electrically equivalent to a capacitor. When the microcontroller drives the piezo with an AC audio signal and then stops, residual electrostatic charge can remain trapped across the crystal element. The 10 kΩ resistor R2 drains this residual charge to ground, silencing the element quickly.

Can I connect an HC-SR04 directly to a 3.3 V microcontroller?

Standard HC-SR04 modules require a 5.0 V supply to power their acoustic transmitters. Because the module runs on 5 V, its ECHO output pin produces a 5.0 V logic HIGH signal. Connecting a 5 V ECHO pin directly to a 3.3 V microcontroller GPIO (such as an ESP32 or STM32) can damage the microcontroller input stage. Use a resistive voltage divider (e.g., 1 kΩ and 2 kΩ) or a dedicated level converter on the ECHO pin for 3.3 V boards.

How accurate is the HC-SR04 ultrasonic distance sensor?

Under controlled room-temperature conditions with a flat, rigid target perpendicular to the sensor axis, the HC-SR04 offers a resolution of approximately 0.1 inches (3 mm) with an effective operating range of 1 inch to 13 feet (2 cm to 400 cm). Accuracy is reduced by temperature fluctuations, air currents, or targets positioned at oblique angles greater than 15 degrees.

Why is a 60 ms delay required between sensor pings?

The HC-SR04 datasheet recommends measurement cycles of at least 60 milliseconds. Ultrasonic waves reflect multiple times off distant walls and room objects. Pinging the sensor too rapidly can cause the receiver to pick up lingering reflections from a previous ping, resulting in false distance readings.

What materials cause poor ultrasonic reflections?

Ultrasonic sensors rely on sound waves reflecting specularly back to the detector. Hard, smooth surfaces (such as drywall, acrylic, glass, and wood) reflect sound cleanly. Soft, porous, or irregular materials (such as thick fabric, foam padding, curtains, or angled cardboard) scatter or absorb acoustic energy, causing premature timeouts.

Can I plug in USB while external 5 V power is connected at J1?

No. Disconnect external 5 V power at J1 before plugging in a USB cable for programming. While some official Arduino boards contain auto-switching power circuitry, many third-party Nano clones omit ideal diode protection, which can allow current to back-feed into your computer's USB port.

How can I verify this perfboard layout before soldering?

Open ToolSphere's perfboard simulator, select the Nano + HC-SR04 and piezo buzzer layout, and run the built-in netlist connection checker. The simulator checks your traces against the schematic, verifying that all power, ground, and signal jumpers are continuous with zero short circuits.

For a related walkthrough, read Arduino Nano on Perfboard: A Layout Guide.

Looking for other tools?

Explore ToolSphere Homepage →