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





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.
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.)
What the pins do, step by step
- The Arduino holds Trig high for 10 microseconds.
- The module sends eight bursts of 40 kHz sound on its own.
- 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
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
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
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
- Parking aids
- Level checks of liquids in open tanks
- Obstacle warnings for small robots
- Learning how timing-based sensors work
- 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?
This build. Cheap, easy, and it works on an Uno or Pro Mini.
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.
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.
The VL53L0X laser time-of-flight sensor. A light beam is not absorbed by soft surfaces the way sound is.
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
- Ultrasonic Tape Measure using Arduino: a pocket tape measure built around the same kind of sensor
- How to Build an HC-SR04 Distance Sensor Circuit: the sensor circuit on its own
- Ultrasonic Range detector using Arduino and the SR04 Ultrasonic sensor: another range detector, with its own code
- Arduino Uno Ultrasonic Range Finder: an Uno range finder with a different wiring layout
- Ultrasonic Distance Sensor in Arduino With Tinkercad: the same measurement in the Tinkercad simulator
Related projects: other distance sensors and uses
- Arduino Ping Ultrasonic Range Finder Code: the three-pin Parallax Ping ultrasonic sensor
- Arduino Sonic range finder with SRF05: the SRF05 ultrasonic sensor
- Homemade Infrared Rangefinder using Arduino: an infrared rangefinder instead of ultrasound
- Water Level Indicator Using Arduino and an Ultrasonic Sensor: measuring a tank from above
- Arduino Ultrasonic Parking Spotter: a parking aid for a garage
Quick answers
From 2 cm to 400 cm according to the manufacturer, with accuracy up to 3 mm in ideal conditions.
The manufacturer suggests a cycle longer than 60 ms, which is at most about 16 readings a second.
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.
The measuring angle is 15 degrees (datasheet p. 1). Anything inside that cone can return the echo, not only the object you aim at.
Echo time in microseconds divided by 58 gives centimetres. Divided by 148 gives inches.
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.
- 💾 Schematic and simulation files (zip)
Zip. Our circuit schematic as a Proteus project (.pdsprj), the program that ran in it and a README, from our run in Proteus 9.0 SP2. - 📄 HC-SR04 ultrasonic sensor datasheet (Elecfreaks)
PDF, 3 pages, about 79 KB. Range, trigger timing, beam angle, the microseconds / 58 formula and the power-up note. Pages 1 to 3. - 📄 HD44780U LCD controller datasheet (Hitachi)
PDF, 60 pages, about 322 KB, document ADE-207-272, Rev. 0.0. The controller on a 16×2 display: pins, 4-bit transfer, character patterns. - 📄 ATmega328P datasheet (Microchip, DS40002061B)
PDF, large file, about 32 MB. The microcontroller on the Uno and the Pro Mini. - 📚 Arduino guide: LCD displays and the LiquidCrystal library
Web page. Official wiring and example sketches for the same display. - 💾 Arduino code and ready-to-upload program (zip)
Zip, a few KB. The Arduino program from this page, the compiled file ready to upload, and a README. It prints the distance in cm and m on the LCD and shows “Out of range” when no echo comes back. Open it in the Arduino IDE, pick your board and upload.
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.
