Skip to content

Sensors · Distance

HC-SR04 Ultrasonic Distance Sensor

The classic 40 kHz ultrasonic range finder: two pins, a 10 µs pulse, and an echo whose width is the distance.

Updated November 16, 2026 2 board guides
HC-SR04 Ultrasonic Distance Sensor

The HC-SR04 ultrasonic sensor measures distance by sending a short burst of 40 kHz sound and timing the echo reflected from an object. The common module is specified for a nominal 2 cm to 400 cm range and uses four connections: VCC, TRIG, ECHO and GND.

To measure distance, a microcontroller holds TRIG HIGH for at least 10 µs, then measures how long ECHO remains HIGH. That pulse is the sound's round-trip travel time, so the one-way distance is calculated as speed of sound × time ÷ 2. Near 20 °C, a useful shortcut is distance in cm ≈ Echo time in µs ÷ 58.

One electrical detail matters: the classic HC-SR04 is powered from 5 V and its ECHO output is typically 5 V. An Arduino Uno can read it directly; an ESP32, ESP8266 or Raspberry Pi needs a suitable voltage divider or level shifter on ECHO. Use the Arduino Uno wiring and code guide or the ESP32 guide with a protected ECHO input to build it safely.

Run the HC-SR04 in your browser

Ready-wired circuit with code. No hardware, no install.

HC-SR04 at a glance

HC-SR04 module, front view, showing the two metal ultrasonic transducers and the 4-pin header

Specifications

Operating voltage
5 V DC (3.3 V variants exist, see below)
Working current
15 mA
Ultrasonic frequency
40 kHz
Range
2 cm to 400 cm
Ranging accuracy
up to 3 mm (best case)
Measuring angle
15°
Trigger input
10 µs TTL pulse
Echo output
TTL pulse, width proportional to distance
Echo logic level
5 V (on the classic module)
Minimum cycle
above 60 ms between measurements
Distance formula
echo µs ÷ 58 = cm
Board size
45 × 20 × 15 mm
Header
4 pins, 2.54 mm pitch

Figures follow the HC-SR04 datasheet (ElecFreaks, as reproduced by SparkFun). Real-world accuracy depends on the target, angle and temperature, and cheap clones vary. The datasheet's 3 mm accuracy is a best case on a flat hard target.

What is on the board

Two metal cans dominate the front: one is the transmitter, one is the receiver. They are matched piezoelectric transducers tuned to 40 kHz, which is why the module cannot be swapped for a generic speaker or microphone. On the back sit a small microcontroller (or a custom IC on some clones), a multi-stage amplifier for the very weak return signal, and the four-pin header.

Because the amplifier is built for faint echoes, the module is sensitive to supply noise. Power it from a clean 5 V rail and keep the wires short.

HC-SR04 module, back view, showing the control chip, amplifier parts and the VCC, Trig, Echo, GND header labels

Pinout

PinNameDescription
1VCC5 V supply. Needs a real 5 V rail, not a 3.3 V pin, to reach rated range.
2TrigTrigger input. Hold HIGH for at least 10 µs to start one measurement. A 3.3 V logic HIGH is accepted.
3EchoOutput. Goes HIGH when the burst is sent and LOW when the echo returns. HIGH time = round trip. Swings to 5 V.
4GNDGround. Must be shared with your microcontroller.

Pin order is printed on the board: VCC, Trig, Echo, GND.

Voltage warning. Trig is an input and is happy with 3.3 V logic. Echo is an output at 5 V. An Arduino Uno reads that fine; an ESP32, ESP8266 or Raspberry Pi GPIO is only rated for 3.3 V and needs a divider or level shifter on this one pin.

How it measures distance

A measurement is four steps:

  1. Your microcontroller raises Trig for 10 µs.
  2. The module sends eight pulses of 40 kHz ultrasound and raises Echo.
  3. The sound reflects off an object and the receiver catches the return.
  4. The module drops Echo. The time Echo stayed high is the round-trip time.

Sound covers the distance twice (out and back), so the one-way distance is half of speed × time. At room temperature sound moves about 343 m/s, which is 0.0343 cm per microsecond, so:

distance (cm) = echo time (µs) × 0.0343 ÷ 2, or the datasheet shortcut, echo µs ÷ 58.

Worked example. Your sketch measures ECHO HIGH for 1,750 µs. Multiply by the speed of sound: 1,750 × 0.0343 = 60.0 cm. That is the round trip, so halve it: the wall is 30.0 cm away. The ÷ 58 shortcut gives 1,750 ÷ 58 = 30.2 cm, close enough for almost every project. Forgetting the ÷ 2 is the most common beginner bug: every reading comes out exactly twice the real distance.

Why 40 kHz? Human hearing tops out around 20 kHz, so the burst is silent to you (a dog may still notice it). A high frequency gives a short wavelength of about 8.6 mm, small enough to bounce cleanly off everyday objects, while still carrying several metres through air.

Timing of one measurement: Trig pulse, eight 40 kHz bursts, then Echo high for the round-trip time

Why a wider pulse means a farther wall

Sound travels at a steady speed, so the farther the wall, the longer the round trip, and the longer ECHO stays HIGH. Watch the green pulse grow as the wall moves away:

ECHO pulse width grows with distance: 10 cm is about 580 µs, 200 cm about 11,600 µs

Echo time and distance

DistanceECHO stays HIGH forNote
2 cmabout 116 µsClosest the sensor can measure
10 cmabout 580 µs
50 cmabout 2,900 µs2.9 ms
100 cmabout 5,800 µs5.8 ms
200 cmabout 11,600 µs11.6 ms
400 cmabout 23,200 µsFarthest the sensor can measure
No objectabout 38 msTypical timeout when no echo returns

Each row is distance × 58 µs per cm (sound at about 343 m/s, round trip). The 38 ms timeout is typical, not a guaranteed datasheet value.

HC-SR04 range, beam angle and target limitations

The common HC-SR04 datasheet lists a 2 cm to 400 cm measuring range and a nominal 15° measuring angle. Treat these as reference conditions, not a promise that every object can be detected throughout a perfect cone. The usable area depends on the target's size, surface, angle, mounting and the particular module.

  • Near limit: The nominal minimum is about 2 cm. Very close targets can fall inside the transducer's ring-down and receiver-recovery region, so do not rely on readings below the specified minimum.
  • The beam spreads: This is not a laser pointer. At longer distances, objects outside the exact centre line may return an echo. The sensor reports a reflected signal it can detect, not a precise point on the target.
  • Best targets: Large, hard surfaces facing the sensor—such as a flat wall or board—usually return a stronger, more repeatable echo.
  • Difficult targets: Soft materials can absorb sound; narrow objects may reflect too little energy; and angled surfaces can reflect sound away from the receiver.
  • Installation matters: Keep brackets, enclosure edges, cables and nearby surfaces out of the sensing path. Mount the module firmly and keep both transducer faces unobstructed.

The diagram below illustrates why a broad, square-on target is easier to measure than a small, soft or angled object.

Flat hard surfaces return a strong echo; tilted or soft surfaces lose it

Temperature compensation: why the distance can drift

The familiar 343 m/s speed-of-sound value is an approximation for air near 20 °C. For a simple dry-air model, use:

c (m/s) ≈ 331.3 + 0.606 × T (°C)

Then calculate one-way distance from the measured round-trip time:

distance (cm) = Echo time (µs) × c (m/s) ÷ 20,000

At 20 °C this is close to the familiar Echo-time ÷ 58 shortcut. As air gets warmer, sound travels faster; if code keeps using the 20 °C constant, the calculated distance tends to read short. In colder air it tends to read long. Humidity and local conditions also affect sound speed, so this is a useful correction model—not laboratory-grade compensation.

For projects that need better repeatability across changing temperatures, measure air temperature with a sensor such as the DS18B20, update the sound-speed calculation, and compare the result with a tape-measured reference distance. The graph below shows the approximate temperature trend.

Approximate speed of sound in dry air rises with temperature; use the formula in this section for a simple compensation model.

Which ultrasonic module?

ModuleVoltageLogicGood for
HC-SR045 V5 V echoGeneral indoor use, robots, learning
HC-SR04P / 3.3 V versions3 to 5.5 V3.3 V safeESP32, ESP8266, Raspberry Pi without a divider
US-1002.4 to 5.5 VMatches supplyBetter accuracy, adds a temperature-compensated serial mode
JSN-SR04T5 V5 V echoWaterproof probe for tanks and outdoor use, larger dead zone

The modules differ in electrical detail more than in how you read them. Check the pin labels and supply range printed on the board before wiring a 3.3 V microcontroller.

How to get stable HC-SR04 readings

Unstable readings are often caused by target geometry, mounting or power quality. Work through these checks before changing the distance formula:

  • Aim squarely at the target. A flat surface facing the transducers gives a stronger return than an angled surface.
  • Keep the acoustic path clear. Breadboard edges, brackets, the table, enclosure lips and cable bundles can create an early reflection.
  • Leave both transducers exposed. Do not cover the metal cans with tape, foam or a sealed plastic window.
  • Use a stable 5 V supply and a common ground. If a servo or motor shares the supply and causes dips or noise, power the motor separately while keeping grounds connected. Local decoupling may help a noisy build, but it does not fix poor target geometry or incorrect wiring.
  • Respect the measurement interval. The common datasheet recommends more than 60 ms between trigger cycles to reduce interference from previous echoes.
  • Filter occasional outliers. Take three to five readings at safe intervals and use the median. Filtering can reject isolated spikes, but it cannot make an unsuitable target detectable.

Save a pin: one-wire (3-pin) mode

Running out of pins on a robot? The HC-SR04 can share one microcontroller pin for TRIG and ECHO. The pin is an output while it sends the 10 µs trigger, then switches to an input and times the echo. Join TRIG and ECHO on the module with a short jumper and run a single signal wire to the board, so the connection becomes VCC, signal and GND.

The NewPing library supports this out of the box: pass the same pin number twice.

sketch.ino
#include <NewPing.h>

#define SONAR_PIN    12   // TRIG and ECHO joined, one wire to D12
#define MAX_DISTANCE 400  // cm

NewPing sonar(SONAR_PIN, SONAR_PIN, MAX_DISTANCE);

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

void loop() {
  delay(60);                        // at least 60 ms between pings
  unsigned int cm = sonar.ping_cm(); // 0 means no echo inside MAX_DISTANCE
  Serial.print(cm);
  Serial.println(" cm");
}

Warning

Use one-pin mode on 5 V boards such as the Uno, Nano or Mega. On an ESP32, keep separate TRIG and ECHO pins: ECHO needs its voltage divider, and a divider on a shared pin also weakens the trigger pulse. Some HC-SR04 clones release the line slowly and return 0 in this mode; if yours does, go back to two pins.

Common HC-SR04 wiring and measurement mistakes

  • Connecting ECHO directly to an ESP32 or Raspberry Pi GPIO. The classic module's ECHO output is around 5 V. Use a divider or level shifter before the 3.3 V input.
  • Triggering too frequently. Allow at least 60 ms between measurements as recommended by the common module datasheet; faster cycles can cause confusing reflections or cross-talk.
  • Omitting a timeout. Arduino's pulseIn() waits up to one second by default if no timeout is supplied. Pass an explicit timeout so a missing echo does not stall the application for a long time.
  • Powering the classic module from 3.3 V and assuming rated performance. Its common specification is 5 V; variants differ, so check the exact module markings and documentation.
  • Expecting every surface to work. Soft, narrow or angled targets may not return enough sound to the receiver.
  • Firing multiple ultrasonic sensors together. Their bursts can interfere. Trigger sensors sequentially and allow the echo cycle to finish before starting another.
Troubleshooting the HC-SR04 by symptom

Where it shines, and where to use something else

Great for obstacle avoidance, parking-style distance beepers, liquid-level checks in clean tanks (from above), presence detection and simple robot navigation. Reach for something else when you need fine resolution at short range (VL53L0X laser time-of-flight), sunlight-proof or mist-proof sensing, or detection of soft and tiny targets.

HC-SR04 and its alternatives at a glance

  • HC-SR04

    Method
    Ultrasonic, 40 kHz
    Range
    2 cm to 4 m
    Output
    Echo pulse (digital)
    Best for
    Cheap obstacle and level sensing indoors
  • JSN-SR04T

    Method
    Ultrasonic, waterproof probe
    Range
    about 25 cm to 4.5 m
    Output
    Echo pulse (digital)
    Best for
    Tanks, outdoors and damp places
  • US-100

    Method
    Ultrasonic
    Range
    2 cm to 4.5 m
    Output
    Echo pulse or serial with temperature compensation
    Best for
    Better accuracy without extra code
  • VL53L0X

    Method
    Laser time-of-flight
    Range
    up to about 2 m
    Output
    I2C
    Best for
    Small targets, tight beam, fine resolution
  • GP2Y0A21

    Method
    Infrared triangulation
    Range
    10 cm to 80 cm
    Output
    Analog voltage
    Best for
    Very short range, quick response

Typical datasheet ranges. Vendors and clones differ, so check the listing for the module you actually buy.

Frequently asked questions

How far can the HC-SR04 measure? The datasheet range is 2 cm to 400 cm. In a real room, expect reliable readings out to about 2 to 3 m on a large, flat, hard target, and less on small or soft ones.

How accurate is it? The datasheet quotes up to 3 mm in the best case. Against a flat wall, a sensor calibrated with a tape measure is usually within a centimetre or two. Air temperature, target angle and supply noise all move that, so see the temperature section above.

Does it work at 3.3 V? The classic module is built for 5 V. It may respond at 3.3 V with reduced range; use an HC-SR04P-type version for a true 3.3 V system.

Why does it read 0, or get stuck on a small number? A reading of 0 (or "no echo") means nothing came back inside your timeout: wrong pins, no 5 V, a target out of range, or one that is too soft or too angled. A small number that never changes usually means something sits inside the beam close to the cans, such as a bracket, a breadboard edge or the table. See the troubleshooting diagram above.

Can I use one pin for TRIG and ECHO? Yes, on 5 V boards. Jumper the two pins together and give NewPing the same pin number twice, as shown in the one-pin mode section above.

Do I need a library? No. pulseIn() on Arduino and ESP32 is enough. A library such as NewPing adds timeouts and median filtering if you want them.

Does pulseIn() block my code? Yes. It waits for the echo, up to the timeout you give it (30 ms in our sketches), so each measurement can pause your loop for that long. That is fine for most projects. If you need tighter timing, use NewPing's timer-based mode or read Echo with a pin-change interrupt.

Can I use more than one sensor? Yes, but never let two fire at the same moment, because each one hears the other's burst. Give every sensor its own Trig and its own Echo pin, and trigger them one at a time with at least 60 ms between measurements.

Does it work in the dark, in sunlight, or through glass? Light makes no difference, because it measures with sound, so it works in the dark and in direct sun. It cannot measure through a window or glass panel, because the sound bounces off the pane. Condensation on the cans and strong air currents can disturb readings.

Is it waterproof? No. Keep the module dry, and for tanks, outdoor use or damp places choose a waterproof probe such as the JSN-SR04T.

Ready to build? Pick your board

Each guide starts from an empty desk, lists every part, and walks you through wiring, uploading and reading your first measurement, with two small projects at the end.

  • Arduino Uno guide. Direct wiring, no extra parts. Includes a parking sensor with buzzer and a touch-free dustbin lid.
  • ESP32 guide. Adds the voltage divider that keeps your board safe, plus a live distance web page on your phone.

Technical references

Wiring & code

Board integration

Library

None — uses built-in pulseIn() by Arduino core

None required. The basic sketch uses only functions built into Arduino. Optional: NewPing by Tim Eckel (install from Library Manager) for median filtering.

This HC-SR04 with Arduino Uno tutorial takes you from the four-wire circuit to a working distance meter in the Serial Monitor. The classic HC-SR04 uses a 5 V supply and a 5 V ECHO output, which is compatible with the Uno's 5 V input. You do not need a resistor divider for this Uno connection.

You will connect TRIG to D9 and ECHO to D10, upload a no-library sketch with an explicit pulse timeout, then extend the build into a parking-distance alert and a touch-free dustbin lid. Start with the HC-SR04 sensor overview if you want the operating principle and measurement limits first.

At a glance

Time
About 15 minutes
Skill level
Complete beginner
Extra parts
None for the basic build
You will learn
Wiring, uploading code, reading the Serial Monitor, how time becomes distance

What you need

Everything in the first table is required. The second table is only for the two projects at the end.

Required parts

  • Arduino Uno (or compatible)

    Qty
    1
    Notes
    Any Uno, clone or Nano-class board works. This guide uses Uno pin names.
  • USB cable

    Qty
    1
    Notes
    The one that fits your board (usually USB-B for a genuine Uno).
  • HC-SR04 ultrasonic sensor

    Qty
    1
    Notes
    Four pins: VCC, Trig, Echo, GND.
  • Breadboard

    Qty
    1
    Notes
    Half-size is plenty.
  • Jumper wires, male to male

    Qty
    4
    Notes
    Different colours help: red, black, plus two others.
  • A computer with the Arduino IDE

    Qty
    1
    Notes
    Free from arduino.cc. We install it in Step 2.

If your jumper wires are male to female, you can skip the breadboard and plug the female ends straight onto the sensor pins.

Optional parts for the projects

PartQtyUsed in
Active buzzer1Project 1: parking sensor
LED (any colour)1Project 1
220 Ω resistor1Project 1 (protects the LED)
SG90 micro servo1Project 2: dustbin lid

Step 1. Wire it up

Unplug the USB cable first. Connecting wires to a powered board is how short circuits happen, so make wiring a habit you do with the power off.

You are making four connections. Two carry power, one tells the sensor to measure, and one brings the answer back:

  • 5V to VCC gives the sensor power.
  • GND to GND completes the circuit. Both devices must share a ground or nothing works.
  • D9 to Trig. The Uno shouts "measure now" on this wire.
  • D10 to Echo. The sensor answers on this wire, and the Uno times the answer.

Here is the same circuit wired in the SolderHub Simulator. Open it from the simulator card further down to run it:

HC-SR04 wired to an Arduino Uno in the SolderHub Simulator: 5V to VCC, D9 to Trig, D10 to Echo, GND to GND

Wiring: HC-SR04 to Arduino Uno

Component pinArduino Uno pinNote
VCC5VRed wire. Power for the sensor.
TrigD9Blue wire. Uno to sensor: start a measurement.
EchoD10Green wire. Sensor to Uno: the timing pulse. The Uno is a 5 V board, so this is safe to connect directly.
GNDGNDBlack wire. Common ground.
  1. 1Push the HC-SR04 into the breadboard so its four pins land in four different rows (the metal cans face away from the board).
  2. 2Red wire: from the Uno's 5V pin to the row of the sensor pin labelled VCC.
  3. 3Black wire: from a Uno GND pin to the row of the sensor pin labelled GND.
  4. 4Blue wire: from Uno pin 9 to the row of the sensor pin labelled Trig.
  5. 5Green wire: from Uno pin 10 to the row of the sensor pin labelled Echo.

Check before plugging in. Trace each wire with your finger: red goes to VCC, black to GND. Swapping those two can damage the sensor. Trig and Echo are harmless if swapped, but nothing will read.

Step 2. Set up the Arduino IDE

If you already upload sketches to your Uno, skip to Step 3.

  1. Download and install the Arduino IDE from arduino.cc.
  2. Plug the Uno into your computer with the USB cable. The small green power light on the board should come on.
  3. Open the IDE. Click Tools > Board and choose Arduino Uno.
  4. Click Tools > Port and choose the port that appeared when you plugged in the board. On Windows it looks like COM3, on Mac /dev/cu.usbmodem..., on Linux /dev/ttyACM0.

Step 3. Upload your first sketch

A sketch is an Arduino program. Copy this one into a new IDE window, replacing everything in it. It uses no library, only functions every Arduino already has.

sketch.ino
// HC-SR04 distance meter - Arduino Uno
const int TRIG_PIN = 9;    // Uno pin D9  -> sensor Trig
const int ECHO_PIN = 10;   // Uno pin D10 <- sensor Echo

void setup() {
  Serial.begin(9600);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  digitalWrite(TRIG_PIN, LOW);   // start with Trig LOW
}

void loop() {
  // 1. Send a 10 microsecond pulse on Trig
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  // 2. Measure how long Echo stays HIGH (in microseconds).
  //    30000 us = give up after 30 ms if no echo comes back.
  unsigned long echoTime = pulseIn(ECHO_PIN, HIGH, 30000UL);

  // 3. Turn time into distance
  if (echoTime == 0) {
    Serial.println("No echo - nothing in range?");
  } else {
    float distanceCm = echoTime / 58.0;
    Serial.print("Distance: ");
    Serial.print(distanceCm, 1);
    Serial.println(" cm");
  }

  delay(500);   // read twice per second
}
  1. 1Click the Upload button (the right arrow at the top left). Wait for "Done uploading".
  2. 2Click Tools > Serial Monitor.
  3. 3At the bottom right of the Serial Monitor, set the speed to 9600 baud. If this does not match the code, you will see random symbols.
  4. 4Hold your hand about 20 cm in front of the sensor, then slowly move it closer and farther.

You should see numbers like these, changing as your hand moves:

Output
Distance: 21.3 cm
Distance: 20.8 cm
Distance: 14.2 cm
Distance: 9.7 cm
Distance: 5.1 cm
No echo - nothing in range?

Seeing numbers? Congratulations, it works. If not, jump to Troubleshooting.

How the sketch works, line by line

You do not need to memorise this, but understanding it turns copy-pasting into building.

The sketch explained

const int TRIG_PIN = 9;
Gives the pin number a name so the code is readable. The sensor's Trig wire is on pin 9.
pinMode(TRIG_PIN, OUTPUT);
Trig is a pin the Uno writes to, so it is an OUTPUT.
pinMode(ECHO_PIN, INPUT);
Echo is a pin the Uno listens to, so it is an INPUT.
digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10);
Raises Trig for 10 microseconds. That is the "measure now" signal.
pulseIn(ECHO_PIN, HIGH, 30000UL);
Waits for Echo to go HIGH, times how long it stays HIGH, and returns that time in microseconds. If nothing returns within 30,000 µs it gives up and returns 0.
echoTime / 58.0
Converts time into centimetres. Sound covers about 1 cm in 29 µs, and the pulse measures out and back, so 58 µs per centimetre of distance.
if (echoTime == 0)
Zero means no echo came back: nothing in front, too far, or the surface is soft or angled.
delay(500);
Waits half a second. The sensor needs more than 60 ms between measurements, so never go faster than that.

Why 58? Speed of sound is about 0.0343 cm per microsecond. Distance = 0.0343 × time ÷ 2, which is time ÷ 58.

Timing diagram: a 10 µs TRIG pulse starts the 40 kHz burst; ECHO HIGH duration represents round-trip travel time.

Try this circuit in the SolderHub Simulator

Run this exact circuit in your browserReady-wired, code loaded

Confirm simulator behavior against the real wiring and the sensor datasheet before connecting hardware.

Experiments: learn what the sensor can and cannot do

Spend five minutes breaking it on purpose. You will avoid hours of confusion later.

Try this

  • Point it at a wall from 30 cm

    What you should see
    A steady number near 30
    Why
    Flat, hard and square-on: the ideal target.
  • Tilt a book at 45° in front of it

    What you should see
    Jumpy numbers or No echo
    Why
    The sound bounces off at an angle and never returns.
  • Hold a pillow or jacket in front

    What you should see
    Weak or missing readings
    Why
    Soft things absorb ultrasound.
  • Move your hand closer than 2 cm

    What you should see
    Nonsense or No echo
    Why
    Too close: the echo returns before the sensor is ready to listen.
  • Point it at the ceiling

    What you should see
    No echo, or a distant number
    Why
    Nothing within range reflects the sound back.
Why some surfaces work and others do not
Theoretical relationship between one-way distance and Echo pulse width at approximately 20 °C.

Make it accurate: calibrate with a tape measure

Cheap sensors are rarely wrong by much, but a two-minute check makes you certain.

  1. Place the sensor 50 cm from a flat wall, measured with a tape from the front of the sensor's cans.
  2. Read the number on the Serial Monitor. Say it shows 51.2 cm.
  3. The difference (-1.2 cm) is your offset. Change the line to float distanceCm = echoTime / 58.0 - 1.2;.

Warm rooms read slightly short and cold rooms slightly long because sound speed changes with temperature. For most projects ignore this. The overview explains how to correct for it.

Easier and steadier: the NewPing library

The plain sketch is perfect for learning. For projects, many people use NewPing by Tim Eckel. It hides the timing code, handles timeouts, and can take several readings and keep the middle one, which removes random spikes.

  1. 1In the Arduino IDE, click the Library Manager icon on the left (the stack of books).
  2. 2Type NewPing in the search box.
  3. 3Find NewPing by Tim Eckel and click Install.
  4. 4Upload the sketch below. Your wiring does not change.
sketch.ino
#include <NewPing.h>

#define TRIG_PIN     9
#define ECHO_PIN     10
#define MAX_DISTANCE 400   // cm, the sensor's limit

NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

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

void loop() {
  // Take 5 readings and keep the middle one: ignores one-off spikes
  unsigned int echoTime = sonar.ping_median(5);
  unsigned int cm = sonar.convert_cm(echoTime);

  if (cm == 0) {
    Serial.println("No echo - nothing in range?");
  } else {
    Serial.print("Distance: ");
    Serial.print(cm);
    Serial.println(" cm");
  }
  delay(300);
}

sonar.ping_median(5) takes five measurements and returns the middle one, so a single bad reading cannot fool you. sonar.convert_cm() turns microseconds into centimetres and returns 0 when there was no echo.

Project 1. Parking sensor

Beeps faster as an object gets closer, like a car's reversing sensor. Add a buzzer and an LED to the circuit you already built.

Extra wiring for Project 1

Active buzzer + leg
Uno D8
Active buzzer - leg
GND
LED long leg (+) through 220 Ω resistor
Uno D7
LED short leg (-)
GND

The sensor stays on 5V, D9, D10 and GND exactly as before. An active buzzer has a + mark and makes sound when given power.

sketch.ino
// Parking sensor: the closer the object, the faster the beeping.
const int TRIG_PIN = 9;
const int ECHO_PIN = 10;
const int BUZZER_PIN = 8;   // active buzzer, + leg to D8
const int LED_PIN = 7;      // LED + 220 ohm resistor to D7

float readCm() {
  digitalWrite(TRIG_PIN, LOW);  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  unsigned long t = pulseIn(ECHO_PIN, HIGH, 30000UL);
  return t == 0 ? -1.0 : t / 58.0;
}

void setup() {
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  pinMode(BUZZER_PIN, OUTPUT);
  pinMode(LED_PIN, OUTPUT);
}

void loop() {
  float cm = readCm();

  if (cm < 0 || cm > 100) {                 // nothing close: stay quiet
    digitalWrite(BUZZER_PIN, LOW);
    digitalWrite(LED_PIN, LOW);
    delay(100);
    return;
  }

  // 100 cm -> 600 ms gap between beeps, 5 cm -> 50 ms (almost continuous)
  int gap = map((long)cm, 5, 100, 50, 600);
  gap = constrain(gap, 50, 600);

  digitalWrite(BUZZER_PIN, HIGH);
  digitalWrite(LED_PIN, HIGH);
  delay(40);
  digitalWrite(BUZZER_PIN, LOW);
  digitalWrite(LED_PIN, LOW);
  delay(gap);
}

Nothing happens beyond 100 cm. Closer than that the buzzer beeps, and the gap between beeps shrinks from about 0.6 seconds at 100 cm down to 0.05 seconds at 5 cm, which sounds almost continuous. The map() line is where distance becomes beep speed. Change 100 and 600 to tune it for your room.

Project 2. Touch-free dustbin lid

Wave a hand or drop rubbish within 20 cm and a servo opens the lid for three seconds, then closes it.

Extra wiring for Project 2

Brown or black (ground)
GND
Red (power)
5V
Orange or yellow (signal)
Uno D6

Small SG90 servos can run from the Uno's 5V for a demo. If the servo jitters or the Uno resets, power the servo from a separate 5 V supply and join its ground to the Uno's GND.

sketch.ino
// Touch-free dustbin lid: opens when something is within 20 cm.
#include <Servo.h>

const int TRIG_PIN = 9;
const int ECHO_PIN = 10;
const int SERVO_PIN = 6;
const float OPEN_BELOW_CM = 20.0;
const unsigned long STAY_OPEN_MS = 3000;

Servo lid;
unsigned long closeAt = 0;

float readCm() {
  digitalWrite(TRIG_PIN, LOW);  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  unsigned long t = pulseIn(ECHO_PIN, HIGH, 30000UL);
  return t == 0 ? -1.0 : t / 58.0;
}

void setup() {
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  lid.attach(SERVO_PIN);
  lid.write(0);                         // lid closed
}

void loop() {
  float cm = readCm();

  if (cm > 0 && cm < OPEN_BELOW_CM) {   // hand or object detected
    lid.write(90);                      // open
    closeAt = millis() + STAY_OPEN_MS;  // restart the 3 second timer
  }

  if (closeAt != 0 && millis() > closeAt) {
    lid.write(0);                       // close
    closeAt = 0;
  }
  delay(60);                            // keep 60 ms between readings
}

The sketch never freezes while the lid is open: it records when to close (closeAt) and keeps measuring, instead of using a long delay(). Using millis() this way is how real projects stay responsive. The delay(60) at the end respects the sensor's minimum 60 ms between measurements.

Troubleshooting

Fix it fast

  • Always "No echo"

    Most likely cause
    Trig and Echo wires on the wrong pins, or VCC not on 5V
    Fix
    Compare wires to the wiring table. Make sure the red wire is on 5V, not 3.3V.
  • Random symbols in Serial Monitor

    Most likely cause
    Baud rate mismatch
    Fix
    Set the Serial Monitor to 9600 baud.
  • Port is greyed out or missing

    Most likely cause
    Cable is charge-only or driver missing
    Fix
    Try another USB cable. Clone boards may need a CH340 driver.
  • Number stuck on a small value

    Most likely cause
    Something is in front of the sensor
    Fix
    Check wires, the breadboard edge or a table lip in front of the cans.
  • Numbers jump around

    Most likely cause
    Soft or angled target, or electrical noise
    Fix
    Aim at a flat surface, use the NewPing median sketch, add a 100 µF capacitor across VCC and GND.
  • Values are 3 to 5 cm off

    Most likely cause
    Cheap module tolerance or temperature
    Fix
    Calibrate with a tape measure.
  • Upload fails: avrdude error

    Most likely cause
    Wrong Board or Port selected
    Fix
    Re-check Tools > Board and Tools > Port.
Arduino Uno troubleshooting: common symptoms, likely causes and fixes

Where to go next

You have a working distance sensor. Good next steps:

  • Read the HC-SR04 overview to understand range, angle and temperature in depth.
  • Build the same circuit on an ESP32 and put the reading on a web page.
  • Compare with a laser sensor, the VL53L0X, when you need millimetre accuracy.

References

Step-by-step

Board guides