Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

To measure distance with an Arduino, connect an HC-SR04 ultrasonic module, send a short trigger pulse, and time the returning echo. The Arduino converts that round-trip time into distance and can print the result to the Serial Monitor. This guide uses an Arduino Uno and shows the wiring, a timeout-safe sketch, and ways to improve unreliable readings.

How ultrasonic distance measurement works

An ultrasonic transmitter emits sound above the range of human hearing; a receiver detects sound reflected from an object. Together, the transmitting and receiving parts form a transceiver. The HC-SR04 has two visible transducers, while its onboard electronics handle the ultrasonic burst and echo timing. The Arduino controls the module and reads its output; it does not normally generate or analyze the 40 kHz sound wave itself.

  1. The Arduino holds TRIG LOW briefly, then sends it HIGH for about 10 microseconds.
  2. The module sends an ultrasonic burst and waits for its reflection.
  3. The module holds ECHO HIGH for the time taken by the sound to travel to the target and back.
  4. The Arduino measures that pulse width and calculates the distance to the reflecting surface from the sensor face.

Sound travels about 343 metres per second in air near room temperature, or about 0.0343 centimetres per microsecond. Since the measured time is a round trip, divide by two:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

distance_cm = echo_time_us × 0.0343 ÷ 2

This is a useful project approximation, not precision metrology. Sound speed changes with air temperature, and the target and installation affect the result.

#1 Best Overall
WWZMDiB 2 Pcs HC-SR04 Ultrasonic Sensor Module Compatible with for Arduino R3 MEGA Mega2560 Duemilanove Nano Robot XBee ZigBee (2 Pcs HC-SR04 Ultrasonic Sensor)
  • HC-SR04 Ultrasonic Sensor:This is a device that can use sound waves to measure the distance of an object. It measures distance by emitting a sound wave of a specific frequency and listening to the bounce of that sound wave. The distance between the sonar sensor and the object can be calculated by recording the time elapsed between the generation of the sound wave and the bounce of the sound wave
  • Working Voltage: 5V DC;Quiescent current: less than 2mA
  • Ranging Distance:2cm - 450 cm;High precision: 0.3 cm
  • Effectual Angle: <15°
  • Test mode :Test distance = ((Duration of high level)*(Sonic :340m/s))/2

Parts and board compatibility

  • An Arduino Uno R3, Uno R4 Minima, Nano, or compatible board.
  • An HC-SR04 module, breadboard, jumper wires, and USB cable.
  • Optionally, an LCD or OLED, LEDs, buzzer, servo, or data logger for a larger project.

The Uno R3 provides 14 digital I/O pins and operates at 5 V, making it a straightforward match for commonly sold 5 V HC-SR04 modules. See the Arduino Uno R3 specifications and the Uno R4 Minima hardware page.

For a 3.3 V board, do not assume the Uno wiring is safe. Check the specific sensor’s supply requirement and the board’s input-voltage tolerance. An HC-SR04 ECHO output may be 5 V; use a resistor divider or suitable level shifter unless the documentation confirms direct compatibility.

Wire the HC-SR04 to an Arduino Uno

HC-SR04 pin Arduino Uno connection
VCC 5V
GND GND
TRIG D9
ECHO D10

D9 and D10 are example choices; other suitable digital pins work if the pin numbers in the sketch match the wiring. Keep the sensor oriented so its transducers face the area being measured.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
ELEGOO 5PCS HC-SR04 Ultrasonic Module Distance Sensor Kit
  • NON-CONTACT DISTANCE SENSING: Add object detection to robot navigation, parking-distance prototypes, automatic lids, counters and interactive projects; each HC-SR04 uses a 40 kHz ultrasonic burst and echo timing to estimate distance
  • 5-PACK FOR REPEATABLE PROTOTYPING: Use multiple HC-SR04 modules across builds, compare sensor positions or keep spares for testing and replacement; each module integrates an ultrasonic transmitter, receiver and control circuit
  • 5 V MODULE WITH 3-450 CM RANGE: Connect VCC, Trig, Echo and GND, use a 10 µs trigger pulse and measure Echo duration; resolution is 0.3 cm with an effective angle under 15°, while the controller board and external power source are not included
  • PROTECT 3.3 V GPIO: The HC-SR04 operates from 5 V and its Echo output is 5 V, so use a voltage divider or suitable level shifting with 3.3 V inputs; keep the module dry and use it for prototyping rather than calibrated measurement
  • FOR ROBOTICS & STEM PROJECTS: Suitable for distance measurement, object detection, automatic lids, parking alerts, robot navigation and other hands-on electronics builds

Upload a working distance-measurement sketch

In the Arduino IDE, select the correct board and port, upload this sketch, then open the Serial Monitor and set its baud rate to 9600.

const byte TRIG_PIN = 9;
const byte ECHO_PIN = 10;

void setup() {
  Serial.begin(9600);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
}

void loop() {
  // Send an approximately 10 microsecond trigger pulse.
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  // Stop waiting if no echo arrives within the timeout.
  unsigned long duration = pulseIn(ECHO_PIN, HIGH, 30000UL);

  if (duration == 0) {
    Serial.println("No echo");
  } else {
    float distanceCm = duration * 0.0343f / 2.0f;
    float distanceIn = distanceCm / 2.54f;

    Serial.print("Distance: ");
    Serial.print(distanceCm, 1);
    Serial.print(" cm (");
    Serial.print(distanceIn, 1);
    Serial.println(" in)");
  }

  delay(60);
}

Move a broad, solid object in front of the sensor and watch the displayed distance change. The pulseIn() function measures a pulse and accepts an optional timeout; the 30,000-microsecond limit here prevents the program from waiting indefinitely when an echo is missing. The timeout is an example, not a universal sensor setting. Choose one appropriate to your intended range. See the Arduino pulseIn() reference.

A timeout is not a valid measurement of zero centimetres. In this sketch, duration == 0 means no HIGH echo pulse arrived before the timeout. A very small nonzero value can indicate a very close target or a spurious reflection; a large or absent value can result from a distant, weakly reflecting target or an installation problem.

Rank #3
MTDELE 5 Pcs HC-SR04 Ultrasonic Sensor Module with 5Pcs Mounting Bracket
  • HC-SR04 Ultrasonic Sensor:Compatible with for Arduino R3 UNO MEGA Mega2560 Duemilanove XBee Nano Robot With 5Pcs mounting bracket
  • Working Voltage: 5V DC; Quiescent current: Less than 2mA
  • Ranging Distance:2 - 450 cm;High precision:0.3 cm;Effectual Angle: < 15°
  • Test distance=((high level duration)*(sound wave: 340m/s))/2
  • Merchandise included:5Pcs HC-SR04 Ultrasonic Sensor;5Pcs Mounting bracket;20Pcs Mounting screw;10Pcs Female to Female Wire; 10Pcs Male to Female Wire

Convert echo time to centimetres or inches

The sketch uses duration × 0.0343 ÷ 2 because duration is in microseconds and 0.0343 is the approximate speed of sound in centimetres per microsecond near room temperature. The division by two accounts for the journey to the target and back. To convert centimetres to inches, divide by 2.54. The integer approximation duration / 58 is also commonly used for centimetres, but it is an approximation as well.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Printing one decimal place only formats the output; it does not guarantee that the measurement is accurate to a tenth of a centimetre. If the project needs better results, compare readings with a ruler at known distances using the final mounting and target. For temperature compensation, measure ambient temperature and adjust the assumed speed of sound; for a hobby demonstration, the room-temperature constant is usually adequate.

When to use a library instead

NewPing

For a single sensor and a first project, raw pulseIn() makes the timing easy to understand. NewPing is an option when maximum-distance limits, median readings, or more structured handling are useful. The Arduino library catalog lists NewPing 1.9.7; check the version and board compatibility in Library Manager when installing because library listings can change. Its documentation describes functions including ping_cm(), ping_in(), and ping_median().

Rank #4
5pcs HC-SR04 Ultrasonic Sensor, Distance Sensor with Ultrasonic Transmitter and Receiver Module Compatible with Ar-duino UNO MEGA2560 Nano Robot XBee ZigBee
  • Test mode :Using IO trigger for high level signal.( Not less that 10us),The Module sends eight 40 kHz automatically and detect whether there is a pulse signal back.
  • The detection zone: 0.78~196 in/ (2cm~500cm); High precision: up to 0.12 in/(0.3 cm) Effectual angle: less than 15°.
  • Power supply: 5V DC; Quiescent current: less than 2mA.
  • Test distance = ((Duration of high level)*(Sonic :340m/s))/2.
  • Package included: 5 x HC-SR04 Ultrasonic Module.
#include <NewPing.h>

const byte TRIG_PIN = 9;
const byte ECHO_PIN = 10;
const unsigned int MAX_DISTANCE_CM = 200;

NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE_CM);

void setup() {
  Serial.begin(9600);
}

void loop() {
  unsigned int distanceCm = sonar.ping_cm();

  if (distanceCm == 0) {
    Serial.println("No echo");
  } else {
    Serial.print(distanceCm);
    Serial.println(" cm");
  }

  delay(60);
}

Install NewPing through the Arduino IDE Library Manager, include the header, and set the trigger pin, echo pin, and maximum range in the constructor. A returned zero still needs to be treated as no valid distance, not as a reading at the sensor face. The catalog entry is at Arduino’s NewPing library page; the library’s documentation is at NewPing’s project wiki.

Arduino Ultrasonic library

Arduino’s library catalog also lists an Ultrasonic library for HC-SR04 and other supported sensors. Its catalog entry lists version 3.0.0, published February 25, 2026; check the current listing and compatibility for your board before installation. It offers a simpler abstraction, while the raw sketch above makes the trigger, echo timing, and conversion explicit. See the Arduino Ultrasonic library page.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Improve stability and diagnose common problems

HC-SR04 modules are commonly listed as 5 V devices operating at 40 kHz, with an approximately 10-microsecond trigger pulse and a nominal 15-degree detection angle. Those are module-specific published characteristics, not guarantees for every clone or installation; check the documentation for the actual module. Adafruit’s listing provides one example of those specifications: HC-SR04 Ultrasonic Sonar Distance Sensor.

Best Value
EPLZON HC-SR04 Ultrasonic Module Distance Sensor fit for Arduino UNO MEGA Nano Robot XBee ZigBee (Pack of 5 pcs)
  • EPLZON HC-SR04 Ultrasonic ranging transducer sensor
  • Test mode: Use IO to trigger high-level signals. (Not less than 10us), the module automatically sends 8 40kHz and detects whether there is a pulse signal return.
  • Detection area: 0.78~196 in/(2cm~500cm); high precision: up to 0.12 inch/(0.3 cm), effective angle: less than 15°; Trigger input pulse width: 10uS
  • Power supply: 5V DC; Quiescent current: less than 2mA;Dimension: 1.77 x 0.78 x 0.59 inches/45mm x 20mm x 15mm(length*width*height)
  • Test distance=((high level duration)*(sound wave: 340m/s))/2

Real-world results depend heavily on what the sound hits. Broad, solid, relatively flat surfaces facing the sensor tend to be easier to measure. Soft or porous materials, narrow objects, irregular targets, or surfaces angled so they reflect sound away can return weak or misleading echoes. A broad beam can also pick up a nearby wall or other object rather than the intended target. Commonly advertised ranges such as 2–400 cm are seller or module claims, not guaranteed usable range or accuracy in every project.

A pause of roughly 50–60 ms between readings is a practical beginner setting that gives echoes time to decay. It is an application choice, not a universal HC-SR04 requirement; range, environment, and other sensors affect a suitable interval. NewPing documentation describes 29 ms as a shortest delay in a common operating example. For several ultrasonic sensors, trigger them sequentially and wait for each echo or timeout before starting the next to reduce crosstalk. Scheduling helps but cannot eliminate all acoustic interference.

Symptom Likely cause What to check
Always prints “No echo” Wiring error, wrong pin assignment, missing common ground, or no usable reflection Check VCC, GND, TRIG, and ECHO connections against the sketch; try a broad, flat target closer to the sensor.
Zero or no reading for a distant target Target beyond usable range, weak reflection, or timeout too short Move the target closer and confirm the timeout suits the intended range.
Values jump around Angled or absorbent target, vibration, side reflections, or acoustic interference Use a broad target facing the sensor, mount it rigidly, reduce vibration, and slow or sequence measurements.
Board resets or behaves inconsistently Power, loose wiring, or breadboard fault Check supply connections, common ground, and jumper placement.
Works on a Uno but not a 3.3 V board Supply or logic-level incompatibility Verify both devices’ voltage requirements and protect the input with a level shifter or divider when needed.
Measures an unexpected nearby object The beam includes a wall, bracket, or other reflecting surface Reposition the module and clear the area in front of it.

If readings remain noisy, collect several samples, discard timeouts, and use the median of the valid readings rather than trusting a single sample. A rigid mount and a consistent target position matter; filtering can reduce outliers but cannot fix a poor reflection or make an unsuitable sensor accurate.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use cases and their limits

  • Robot obstacle detection: Useful for a low-cost prototype, but do not rely on it as the sole collision-prevention system where failure could injure someone.
  • Parking or hand-distance indicator: Works when the intended surface is large enough and lies within the useful beam.
  • Liquid-level estimate: Mount the sensor above the liquid and point it downward. Measure the air gap, then calculate liquid level = tank reference height − measured air gap. Ripples, foam, condensation, vapors, tank shape, and the sensor’s dead zone can affect the result.
  • Moving-object speed: A single distance reading does not provide velocity. Estimate speed by recording distance over time and accounting for noise and sampling interval.

Do not use a basic hobby module as the sole sensor for a safety system, critical industrial control, or overflow protection without an independent backup. Those uses call for hardware selected and validated for the application.

Choose a different sensor when the project needs it

Sensor type Good fit Trade-offs
HC-SR04 ultrasonic Learning time-of-flight basics and low-cost prototypes with suitable targets Needs clear acoustic reflections; beam, target material, mounting, and electrical compatibility can limit results.
Infrared proximity Short-range detection where a fast, inexpensive sensor is appropriate Surface color and reflectivity, ambient light, and nonlinear output can affect readings.
Optical time-of-flight or LiDAR Compact, directional ranging with a narrower field of view than a basic ultrasonic module Optical performance can depend on reflectivity and ambient light; wiring and libraries differ, and transparent or glossy targets can be difficult.
UART ultrasonic sensor Installations needing a serial interface or a more robust, longer-range product Requires serial configuration and different wiring, power, and budget than an HC-SR04.

Arduino’s Modulino Distance is a compact time-of-flight option with Qwiic-style connections and support listed for the UNO R4 WiFi; it is not a TRIG/ECHO drop-in replacement. See the Modulino Distance product page and Arduino’s Modulino Distance hardware page.

For an ultrasonic sensor with a UART interface, Arduino’s US store listing for the URM06 specifies a 20 cm–10 m range, 1 cm resolution, and a 15-degree detection angle. These are product-specific listed claims, not measurements guaranteed for all installations; check current specifications and availability. See the URM06 product page.

Quick Recap

Bestseller No. 1
WWZMDiB 2 Pcs HC-SR04 Ultrasonic Sensor Module Compatible with for Arduino R3 MEGA Mega2560 Duemilanove Nano Robot XBee ZigBee (2 Pcs HC-SR04 Ultrasonic Sensor)
WWZMDiB 2 Pcs HC-SR04 Ultrasonic Sensor Module Compatible with for Arduino R3 MEGA Mega2560 Duemilanove Nano Robot XBee ZigBee (2 Pcs HC-SR04 Ultrasonic Sensor)
Working Voltage: 5V DC;Quiescent current: less than 2mA; Ranging Distance:2cm - 450 cm;High precision: 0.3 cm
$5.99
Bestseller No. 3
MTDELE 5 Pcs HC-SR04 Ultrasonic Sensor Module with 5Pcs Mounting Bracket
MTDELE 5 Pcs HC-SR04 Ultrasonic Sensor Module with 5Pcs Mounting Bracket
Working Voltage: 5V DC; Quiescent current: Less than 2mA; Ranging Distance:2 - 450 cm;High precision:0.3 cm;Effectual Angle: < 15°
$9.99
Bestseller No. 4
5pcs HC-SR04 Ultrasonic Sensor, Distance Sensor with Ultrasonic Transmitter and Receiver Module Compatible with Ar-duino UNO MEGA2560 Nano Robot XBee ZigBee
5pcs HC-SR04 Ultrasonic Sensor, Distance Sensor with Ultrasonic Transmitter and Receiver Module Compatible with Ar-duino UNO MEGA2560 Nano Robot XBee ZigBee
Power supply: 5V DC; Quiescent current: less than 2mA.; Test distance = ((Duration of high level)*(Sonic :340m/s))/2.
$14.50
Bestseller No. 5
EPLZON HC-SR04 Ultrasonic Module Distance Sensor fit for Arduino UNO MEGA Nano Robot XBee ZigBee (Pack of 5 pcs)
EPLZON HC-SR04 Ultrasonic Module Distance Sensor fit for Arduino UNO MEGA Nano Robot XBee ZigBee (Pack of 5 pcs)
EPLZON HC-SR04 Ultrasonic ranging transducer sensor; Test distance=((high level duration)*(sound wave: 340m/s))/2
$9.99

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.