Verified by our editorial teamSimulated in Proteus 9.0 SP2

Arduino Based Distance Measurement using Ultrasonic Sensor

Summary of Arduino Based Distance Measurement using Ultrasonic Sensor This project utilizes an Arduino Pro Mini and an HC-SR04 ultrasonic sensor to measure obstacle distances precisely without contact. By transmitting 40 KHz sound waves and calculating the echo return time, the system determines distance using the known speed of sound. The setup includes a 16x2 […]

Avatar of Ibrar Ayyub
By Ibrar Ayyub
Published July 10, 2017
At a glance
CategorySensor – Transducer – Detector Projects
DifficultyBeginner
IncludesCode, Diagrams, Datasheets
UpdatedDecember 1, 2026
Reading timeabout 11 min
On this page

Summary of Arduino Based Distance Measurement using Ultrasonic Sensor


This project utilizes an Arduino Pro Mini and an HC-SR04 ultrasonic sensor to measure obstacle distances precisely without contact. By transmitting 40 KHz sound waves and calculating the echo return time, the system determines distance using the known speed of sound. The setup includes a 16x2 LCD for display and is powered by a 9V battery.

Parts used in the Ultrasonic Distance Measurement Project:

  • Arduino Pro Mini
  • Ultrasonic sensor Module
  • 16x2 LCD
  • Scale
  • Bread board
  • 9 volt battery
  • Connecting wires
12 min read

The HC-SR04 is one of the simplest ways to give an Arduino a sense of distance: one sensor, one display and about thirty lines of code. This page explains how the build works, what every wire does, where it tends to go wrong, and what we think of it.

HOW THIS PAGE WAS CHECKED

Datasheet verified by us. The trigger pulse, echo timing, range and beam angle were checked against the HC-SR04 datasheet. Page numbers are quoted where each figure is used, and the datasheets are linked in the resources box below.

Simulated in Proteus 9.0 SP2, run by us. We built the circuit and ran the sketch ourselves in Proteus 9.0 SP2 Professional (Build 40482). The screenshots and the files we used are on this page. The sketch was run unchanged on a simulated ATmega328P at 16 MHz with an LM016L display. Proteus has no HC-SR04 model, so a second simulated chip produced the trigger-to-echo timing of known distances. Echo widths for 10, 50 and 100 cm showed 10.0, 50.0 and 99.3 cm, and with no echo the display showed “Out of range”. This checks the code, the wiring and the maths; the sound and the real sensor were not simulated. See the screenshots and download the files.

IN SHORT
  • The HC-SR04 times an ultrasound echo, and the Arduino turns that time into a distance.
  • It needs 5 V, two digital pins and a 16×2 LCD, and it measures from 2 cm to 4 m.
  • Most failures come from three things: LCD contrast, the battery connection and soft or angled targets.
  • For tanks, close range or soft surfaces, another sensor is the better pick (see the comparison below).
2 to 400 cm
measuring range
3 mm
accuracy, ideal conditions
5 V
supply voltage
10 µs
trigger pulse

Our Proteus simulation: schematic, screenshots and files

We ran the sketch from this page, unchanged, in Proteus 9.0 SP2 Professional. Proteus has no HC-SR04 model, so a second simulated chip, running a small sketch we wrote, produced the trigger-to-echo timing of known distances. The results below are our own screenshots. Click any screenshot to enlarge it.

Proteus 9.0 SP2 schematic of the HC-SR04 distance meter with an LCD showing 50 cm
Our Proteus schematic: the ATmega328P running the sketch, the LM016L display and the chip that stands in for the sensor.
Proteus LCD showing Dist: 10.0 cm
Echo width 582 microseconds: display shows 10.0 cm (formula gives 9.9 cm).
Proteus LCD showing Dist: 50.0 cm
Echo width 2941 microseconds: display shows 50.0 cm.
Proteus LCD showing Dist: 99.3 cm
Echo width 5831 microseconds: display shows 99.3 cm (formula gives 99.1 cm).
Proteus LCD showing Out of range
No echo pulse: display shows “Out of range” after the 30 ms timeout.
💾 Download our simulation files (hc-sr04-distance-meter-proteus-files.zip)
Zip with the compiled .hex, the Arduino sketch, the Proteus project (.pdsprj), the stand-in sketch and its echo hex files, and a README. Open the .pdsprj in Proteus 9.0 SP2 or newer, check the Program File path points to the .hex, and press Play.

What this proves: the code, the wiring and the maths. What it does not: the real sensor, the sound and the 5 V levels.

How the sensor measures distance

The Arduino sends a short pulse to the sensor. The sensor sends out ultrasound and listens for the echo. The Arduino times the echo and turns that time into a distance, which this project prints on a 16×2 display in centimetres and metres.

HC-SR04 object sound goes out echo comes back distance = (time x speed of sound) / 2

The sound travels to the object and back, so we divide by two. With the time in microseconds and the speed of sound taken as 340 m/s, the formula becomes time * 340 / 20000 centimetres, which is very close to time * 0.017. (The datasheet gives a shortcut, microseconds divided by 58, which assumes a slightly higher speed of sound and differs by about 1 percent. See the comparison table below.)

Temperature changes the answer. Sound is faster in warm air. A good approximation is 331.4 + 0.606 x T metres per second (T in degrees Celsius), so about 343 m/s at 20 C. A fixed 340 m/s is fine for a demo, but the room temperature moves the result by centimetres at a few metres. In a 20 C room the real speed is about 343 m/s, so the display reads roughly 1 percent short (about 3 cm at 3 m). In a 0 C room it reads roughly 2.6 percent long (almost 8 cm at 3 m). The 3 mm accuracy in the datasheet is for ideal conditions: a flat surface facing the sensor straight on.

What the pins do, step by step

Trig 10 µs Sound 8 bursts at 40 kHz (not to scale) Echo echo high for the round trip time

  1. The Arduino holds Trig high for 10 microseconds.
  2. The module sends eight bursts of 40 kHz sound on its own.
  3. If something reflects the sound, the Echo pin goes high for as long as the round trip took. That time is what the Arduino measures.

What you need

Arduino Uno or Pro Mini (5 V board)
HC-SR04 ultrasonic module
16×2 LCD (HD44780 type)
Breadboard and jumper wires
9 V battery (portable use)
Ruler or tape measure
10 k potentiometer for LCD contrast

Uploading the sketch: an Uno uploads over its USB cable. A Pro Mini has no USB port, so it needs a 5 V USB-to-serial adapter connected to its GND, TXD, RXD and DTR pins, with the board set to Arduino Pro or Pro Mini, ATmega328P at 5 V and 16 MHz. The LCD here is the bare 16-pin parallel type, not one with an I2C backpack.

Wiring

HC-SR04 VCC GND Trig Echo Arduino 5VGNDA4 (pin 18)A5 (pin 19) D2D3D4 D5D6D7 5VGND 16×2 LCD RSEND4D5 D6D7VDDVSS, RW V0 (LCD contrast) goes to the middle pin of a 10 k pot, outer pins to 5V and GND. Backlight A: 5V through 220 ohm (many modules have one), K: GND.

Connection table

Arduino pin Goes to
5V HC-SR04 VCC, LCD VDD, top end of the contrast pot
GND HC-SR04 GND, LCD VSS and RW, bottom end of the contrast pot
A4 (pin 18) HC-SR04 Trig
A5 (pin 19) HC-SR04 Echo
D2 LCD RS
D3 LCD EN
D4, D5, D6, D7 LCD D4, D5, D6, D7 (in that order)
Middle pin of the pot LCD V0 (contrast)

RS and EN are on D2 and D3. D4 to D7 carry the data. Do not swap RS and EN with the data lines.

Details that stop this build working

Blank screen is usually contrast. If the display shows nothing, or a row of solid blocks, adjust the contrast on V0. A display with V0 left unconnected often looks dead even when everything else is right.
A4 and A5 are used as ordinary digital pins. On an Uno or Pro Mini they are also the I2C pins. That is fine here, but you cannot add an I2C device on those pins at the same time.
Check the battery connection before powering up. On a 5 V Pro Mini the 9 V battery goes to the RAW pin, not to VCC. Putting 9 V on VCC can destroy the board. The HC-SR04 needs 5 V, so a 3.3 V board will not drive it reliably.
Random resets or jumpy readings? Look at the power. A small 9 V block battery has little current to give, and its voltage sags when the sensor fires or the LCD backlight is on. That can cause reboots and erratic readings. A USB power bank or a 4 x AA battery holder is steadier for a portable build.
Two more warnings from the datasheet. Connect the module’s GND first if you plug it in while the circuit is powered, otherwise it can misbehave. And aim it at a target of at least 0.5 square metres with a surface as flat and smooth as possible, or the reading will suffer. The measuring angle is 15 degrees.

The code

The logic is simple: send the trigger pulse, time the echo, convert to centimetres, print. The sketch adds a timeout on pulseIn, so the display says “Out of range” instead of showing 0 when nothing reflects the sound.

// duino4projects.com
#include <LiquidCrystal.h>

const int TRIG = 18;                 // A4 used as a digital pin
const int ECHO = 19;                 // A5 used as a digital pin
LiquidCrystal lcd(2, 3, 4, 5, 6, 7); // RS, EN, D4, D5, D6, D7

void setup() {
  lcd.begin(16, 2);
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT);
  lcd.print("Distance Meter");
  delay(1500);
}

void loop() {
  digitalWrite(TRIG, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG, LOW);

  unsigned long t = pulseIn(ECHO, HIGH, 30000UL); // wait at most 30 ms
  lcd.clear();
  float cm = t * 0.017;                            // t in microseconds
  if (t == 0 || cm < 2.0 || cm > 400.0) {          // no echo, or outside the 2 to 400 cm range
    lcd.print("Out of range");
  } else {
    lcd.print("Dist: ");
    lcd.print(cm, 1);
    lcd.print(" cm");
    lcd.setCursor(0, 1);
    lcd.print(cm / 100.0, 2);
    lcd.print(" m");
  }
  delay(500);
}

Why 30000? pulseIn counts in microseconds, so 30000 is 30 ms. The sensor’s 4 m limit is a round trip of about 23.5 ms (400 / 0.017 = 23,529 microseconds), so 30 ms leaves a safety margin. If nothing comes back, pulseIn gives up after 30 ms and returns 0, and the sketch shows “Out of range”. A reading outside 2 to 400 cm (datasheet p. 1) is shown the same way. The first line is kept short (“Dist: 50.0 cm” is 13 characters) so it fits the 16 columns of the display. Without the timeout it waits up to a second by default, which makes the display freeze.

The manufacturer suggests a measuring cycle of more than 60 ms so one echo does not mix with the next trigger, so the half-second delay is safe. The datasheet also gives a shortcut: microseconds divided by 58 equals centimetres, which is within about 1.4 percent of our * 0.017.

Where it works well, and where it does not

Good for
  • Parking aids
  • Level checks of liquids in open tanks
  • Obstacle warnings for small robots
  • Learning how timing-based sensors work
Weak at
  • Soft or angled surfaces (fabric, foam, a tilted wall)
  • Objects closer than 2 cm
  • Thin objects: the beam is a wide cone and reports the nearest thing in it
  • Rain, or anything needing millimetre accuracy at long range

Ultrasonic sensor options, and other ways to measure distance

The HC-SR04 ultrasonic sensor we used is not the only choice. Here is how it stacks up against the common alternatives, so you can pick the right one before you wire anything. Figures are typical and differ between suppliers, so check the datasheet for the exact part you buy.

Distance sensor How it measures Range (rough) Connection Watch out for
HC-SR04 ultrasonic sensor (this project) Ultrasound echo 2 to 400 cm 4 pins, any two digital pins Soft or angled targets, 15 degree cone, 5 V only
HC-SR04 with the NewPing library Same sensor, library does the timing Same Same One more library to install, but shorter sketches
JSN-SR04T waterproof ultrasonic sensor Ultrasound, sealed probe on a cable About 25 to 450 cm (Circuit Digest article); some listings claim up to 600 cm Trigger and echo, like the HC-SR04 Bigger dead zone close up, versions differ, some libraries do not work with every version
VL53L0X laser time-of-flight sensor Laser time of flight Up to about 2 m I2C, 2 signal wires Shorter range, needs a library, check the voltage level of your breakout board
Sharp GP2Y0A21YK infrared distance sensor Infrared triangulation Short, roughly 10 to 80 cm 1 analog wire, no library Dark, glossy or clear surfaces and the colour of the target change the reading

Which one should you pick?

A simple display from 2 cm to 4 m
This build. Cheap, easy, and it works on an Uno or Pro Mini.
Cleaner code, several sensors
The same HC-SR04 ultrasonic sensor with the NewPing library. It handles the pulse and the echo timing and also works with some other ultrasonic sensors.
Water tank or outdoors
The JSN-SR04T waterproof ultrasonic sensor. The probe is sealed and the electronics stay dry. Mount it at the top and subtract the reading from the tank height to get the water level.
Close range, soft or angled targets
The VL53L0X laser time-of-flight sensor. A light beam is not absorbed by soft surfaces the way sound is.
Tiny, short-range, no library
The Sharp GP2Y0A21YK infrared distance sensor. One analog read and done, if the target is not dark, glossy or clear.

Project variants: the same ultrasonic sensor, a different build

Related projects: other distance sensors and uses

Quick answers

How far can the HC-SR04 measure?
From 2 cm to 400 cm according to the manufacturer, with accuracy up to 3 mm in ideal conditions.
How often can I take a reading?
The manufacturer suggests a cycle longer than 60 ms, which is at most about 16 readings a second.
Can I use it with a 3.3 V board?
The standard module is specified for 5 V, so use a 5 V board. Some boards sold as 3.3 V versions exist, so check the listing.
How wide is the beam?
The measuring angle is 15 degrees (datasheet p. 1). Anything inside that cone can return the echo, not only the object you aim at.
What is the quick formula?
Echo time in microseconds divided by 58 gives centimetres. Divided by 148 gives inches.
Why does it read badly on cloth or foam?
Soft surfaces absorb sound, so little of it comes back. A hard, flat surface facing the sensor works best.

Check your own build

Put a flat object at 10 cm, 50 cm and 100 cm from the sensor, measured with a ruler, and compare the display with the ruler. If every reading is off by a few centimetres, look at the 5 V supply (a weak battery lowers the sensor’s output) and at the angle of the target.

Project resources and downloads

Datasheets and documents for the parts in this build. Page numbers quoted on this page refer to these files.

Share this project
X
LinkedIn
Reddit
WhatsApp

Quick Solutions to Questions related to Ultrasonic Distance Measurement Project:

  • What is the primary function of the ultrasonic sensor in this project?
    The sensor measures the distance of an obstacle from the sensor.
  • How does the ultrasonic sensor determine distance?
    It calculates distance based on the travelling time of outgoing and returning sound waves.
  • What is the operating range of the HC-SR04 module?
    The module measures distance in a range of 2cm to 400cm.
  • What signal duration is sent using the Trigger pin?
    A high level signal is sent for 10us using the Trigger.
  • At what frequency does the module send ultrasound signals?
    The module sends eight 40 KHz signals automatically.
  • Why is the product of speed and time divided by two?
    The division accounts for the total time taken to reach the obstacle and return back.
  • What formula is used to calculate the distance?
    The formula used is Distance equals Time multiplied by Speed of Sound in Air divided by two.
  • What component is used to display the measured distance?
    A 16x2 LCD is used to display the results.
Scroll to Top