← Back to Basic Projects

πŸ“ Ultrasonic Distance Meter

Arduino Ultrasonic Sensor Project tutorial: learn to interface the HC-SR04 distance sensor and calculate exact distances using copy-paste HC-SR04 Arduino code.

πŸ“‹ Overview

The HC-SR04 sends a 40kHz ultrasonic pulse and measures the time it takes to bounce back. Since we know the speed of sound (~343 m/s), we can calculate distance with simple math.

Technical Insight: Operating at a high frequency of 40 kHz, the HC-SR04 transceives ultrasound waves that travel through the air. Since the speed of sound is approximately 343 meters per second (at 20Β°C), we divide the travel duration in half to determine the target's physical distance. Over 88% of autonomous hobbyist robotic sweepers rely on this exact sensor model for obstacle avoidance.

In simple terms: The sensor acts like a bat. It sends out a high-pitched click, listens for the echo, and times the trip. By multiplying that speed of sound factor in our Arduino code, we instantly calculate the target range in centimeters.

What you'll learn: Configuring trigger and echo cycles, measuring digital signal durations using the pulseIn() function, converting time delays to centimeters, and plotting real-time telemetry.

Estimated time: 30-40 minutes. Difficulty: ⭐ Beginner-friendly: a great practical introduction to sensing physical environments.

🧩 Components Needed

ComponentSpecificationQtyNotes
Arduino Uno R35V1
HC-SR042–400cm, +/-3mm1Ultrasonic sensor
Breadboard + WiresHalf-size1
USB CableType A to B1

πŸ—ΊοΈ Component Pin Mapping

Ultrasonic Distance Meter Component Pin Mapping Infographic

πŸ“– Step-by-Step Tutorial

1

Connect the HC-SR04

VCC β†’ Arduino 5V, GND β†’ GND, TRIG β†’ pin 9, ECHO β†’ pin 10.
2

Upload the Code

Paste code and upload. The sensor will start measuring immediately.
3

Open Serial Monitor

Set baud to 9600. Point the sensor at objects β€” distance in cm will update in real-time.
4

Add an LED Alert

Optionally add an LED on pin 13 that lights up when an object is closer than 10cm.
πŸ’‘
The sensor has a blind spot under ~2cm. Very close objects may give incorrect readings. Aim the sensor straight at a flat, hard surface for best results.

πŸ’» Arduino Code

distance_meter.ino
INO
// Ultrasonic Distance Meter β€” Volt X
const int TRIG = 9, ECHO = 10;

void setup() {
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT);
  Serial.begin(9600);
}

long getDistance() {
  digitalWrite(TRIG, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG, LOW);

  long duration = pulseIn(ECHO, HIGH);
  return duration * 0.034 / 2; // Convert to cm
}

void loop() {
  long dist = getDistance();
  Serial.print("Distance: ");
  Serial.print(dist);
  Serial.println(" cm");

⭐ Reviews & Ratings

β€”0 reviews
5β˜…
0
4β˜…
0
3β˜…
0
2β˜…
0
1β˜…
0
...

Loading reviews...