📘 MODULE 5 – Ultrasonic Distance Meter
Lesson 5.3 – Distance Measurement Code
Learning Objectives
By the end of this lesson, students will be able to:
- Understand how Arduino measures distance using an ultrasonic sensor.
- Learn the purpose of each line in the distance measurement program.
- Generate ultrasonic trigger pulses from Arduino.
- Receive and measure echo signals from the sensor.
- Calculate distance using Arduino code.
- Display measured distance on the Serial Monitor.
- Upload and test the distance measurement program successfully.
Main Content
Introduction
In the previous lesson, we connected the HC-SR04 ultrasonic sensor with Arduino UNO. The hardware setup is now ready.
The next step is to write the Arduino program that allows the sensor to measure distance.
The ultrasonic sensor works by:
- Sending an ultrasonic sound wave.
- Waiting for the reflected wave to return.
- Measuring the travel time.
- Calculating the distance from the travel time.
Arduino performs all these tasks using a simple program.
Complete Distance Measurement Code
const int trigPin = 9;
const int echoPin = 10;
long duration;
float distance;
void setup()
{
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop()
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.0343 / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(500);
}
Understanding the Program
Let us understand the code section by section.
Step 1: Define Pin Numbers
const int trigPin = 9;
const int echoPin = 10;
Explanation
The ultrasonic sensor has two important pins:
- Trigger Pin (TRIG)
- Echo Pin (ECHO)
We connect:
- TRIG → Arduino Pin 9
- ECHO → Arduino Pin 10
These lines store pin numbers in variables.
Step 2: Create Variables
long duration;
float distance;
duration
Stores the time taken by the sound wave to travel.
Example:
duration = 1500;
means the sound wave took 1500 microseconds.
distance
Stores the calculated distance.
Example:
distance = 25.5;
means the object is 25.5 cm away.
Step 3: Setup Function
void setup()
{
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
Serial.begin(9600)
Starts communication between Arduino and the computer.
Serial.begin(9600);
9600 is the communication speed.
pinMode()
pinMode(trigPin, OUTPUT);
TRIG sends signals.
Therefore it is OUTPUT.
pinMode(echoPin, INPUT);
ECHO receives signals.
Therefore it is INPUT.
Step 4: Send Trigger Pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
First, make TRIG pin LOW.
This ensures a clean pulse.
Next:
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
TRIG stays HIGH for 10 microseconds.
This tells the sensor:
“Send an ultrasonic sound wave now.”
After that:
digitalWrite(trigPin, LOW);
The pulse is completed.
The sensor immediately transmits ultrasonic waves.
Step 5: Read Echo Signal
duration = pulseIn(echoPin, HIGH);
pulseIn()
This function measures how long a pin stays HIGH.
Arduino waits until:
- Echo pin becomes HIGH.
- Echo pin becomes LOW again.
- Time is measured.
The measured value is stored in microseconds.
Example:
duration = 2000;
means sound traveled for 2000 microseconds.
Step 6: Calculate Distance
distance = duration * 0.0343 / 2;
This is the most important line of the program.
The speed of sound is approximately:
0.0343 cm per microsecond
Distance traveled:
Distance = Time × Speed
However, the sound travels:
- From sensor to object
- Object back to sensor
So total distance is double.
Therefore:
Actual Distance =
(Time × Speed) ÷ 2
Arduino performs this calculation automatically.
Distance Formula
d=t×0.03432d=\frac{t\times 0.0343}{2}
Where:
- d = Distance in centimeters
- t = Time in microseconds
Step 7: Display Distance
Serial.print("Distance: ");
Prints text.
Output:
Distance:
Serial.print(distance);
Prints the measured value.
Example:
Distance: 23.4
Serial.println(" cm");
Prints unit and moves to next line.
Final output:
Distance: 23.4 cm
Step 8: Delay
delay(500);
Waits 500 milliseconds.
This prevents the Serial Monitor from updating too fast.
Program Flow
The Arduino continuously repeats:
Start
↓
Send Trigger Pulse
↓
Sensor Sends Ultrasonic Wave
↓
Wave Hits Object
↓
Wave Returns
↓
Read Echo Time
↓
Calculate Distance
↓
Display Distance
↓
Repeat
Example Calculation
Suppose:
Duration = 1000 microseconds
Using the formula:
Distance = 1000 × 0.0343 ÷ 2
Distance = 17.15 cm
Arduino automatically performs this calculation.
Expected Serial Monitor Output
If objects are moved in front of the sensor:
Distance: 10 cm
Distance: 15 cm
Distance: 22 cm
Distance: 35 cm
Distance: 50 cm
Values continuously change according to object position.
Common Beginner Mistakes
Wrong Pin Numbers
Incorrect:
const int trigPin = 8;
const int echoPin = 9;
while wiring is connected to Pins 9 and 10.
Always match code with wiring.
Missing Serial.begin()
Without:
Serial.begin(9600);
nothing appears on the Serial Monitor.
Incorrect Trigger Pulse
The trigger pulse must be:
HIGH for 10 microseconds
Otherwise measurements may fail.
Loose Wiring
Loose connections can cause:
- Random readings
- 0 cm readings
- No readings
Always verify connections.
Real-World Examples
Automatic Parking System
Measures vehicle distance from walls or barriers.
Water Tank Monitoring
Measures water level inside tanks.
Obstacle Detection Robot
Detects nearby objects and avoids collisions.
Smart Dustbin
Detects hand movement and opens the lid automatically.
Security Systems
Detects movement near protected areas.
Best Practices
Keep Sensor Stable
Do not shake the sensor while measuring.
Use Proper Power Supply
Provide stable 5V power to the sensor.
Avoid Soft Surfaces
Soft materials absorb sound waves and may produce inaccurate readings.
Test Multiple Distances
Verify readings at:
- 10 cm
- 20 cm
- 30 cm
- 50 cm
to ensure proper operation.
Organize Wiring
Use short and secure jumper wires for reliable results.
Summary
In this lesson, we learned how Arduino measures distance using the HC-SR04 ultrasonic sensor. The Arduino sends a trigger pulse, receives the echo signal, measures travel time, and calculates distance using the speed of sound formula. The measured distance is then displayed on the Serial Monitor. This program forms the foundation for many distance-based Arduino projects such as robots, parking systems, smart bins, and automation systems.
Key Terms
- Ultrasonic Sensor
- HC-SR04
- Trigger Pin
- Echo Pin
- pulseIn()
- Microsecond
- Distance Measurement
- Serial Monitor
- Speed of Sound
- Trigger Pulse
Quiz
1. Which Arduino function measures the echo pulse duration?
A. digitalRead()
B. pulseIn()
C. analogRead()
D. delay()
Answer: B
2. Which pin sends ultrasonic waves?
A. Echo Pin
B. GND
C. Trigger Pin
D. VCC
Answer: C
3. Why is the calculated distance divided by 2?
A. To reduce error
B. Sound travels to the object and back
C. Sensor limitation
D. To convert units
Answer: B
4. What is the typical trigger pulse duration?
A. 1 ms
B. 100 ms
C. 10 microseconds
D. 1 second
Answer: C
5. Which function starts serial communication?
A. Serial.print()
B. Serial.begin()
C. Serial.read()
D. Serial.write()
Answer: B
Assignment
Practical Task
Build the ultrasonic sensor circuit and upload the distance measurement code.
Perform the following tests:
- Place an object at approximately 10 cm.
- Record the displayed distance.
- Repeat for 20 cm.
- Repeat for 30 cm.
- Repeat for 50 cm.
Create a table containing:
| Actual Distance | Measured Distance |
|---|---|
| 10 cm | ____ |
| 20 cm | ____ |
| 30 cm | ____ |
| 50 cm | ____ |
Compare the readings and note any differences.