Build a handheld device that measures how far away an object is using the HC-SR04 ultrasonic sensor.
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.
What you'll learn: pulseIn(), TRIG/ECHO sensor protocol, microseconds→cm conversion, and Serial Monitor output.
Estimated time: 30–40 minutes. Difficulty: ⭐ Beginner-friendly.
| Component | Specification | Qty | Notes |
|---|---|---|---|
| Arduino Uno R3 | 5V | 1 | |
| HC-SR04 | 2–400cm, ±3mm | 1 | Ultrasonic sensor |
| Breadboard + Wires | Half-size | 1 | |
| USB Cable | Type A to B | 1 |
9600. Point the sensor at objects — distance in cm will update in real-time.// 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");
delay(300);
}Sign in to leave a review
No reviews yet. Be the first to share your experience!