Ultrasonic Distance Meter
Measure distance using HC-SR04 ultrasonic sensor.
- Intermediate
- Sensors
- 2 parts
Opens in your browser with the parts, wiring and code already in place. Press Run to watch it work, then change anything you like.
How it works
An HC-SR04 ultrasonic sensor measures distance by timing an echo. The Arduino sends a short pulse on pin 7 (TRIG), the sensor sends out a burst of ultrasound, and then the sensor holds pin 6 (ECHO) high for as long as the sound takes to reach an object and bounce back.
The sketch makes a clean 10-microsecond pulse on TRIG, then pulseIn(ECHO, HIGH) measures how many microseconds ECHO stays high. Sound travels about 0.034 centimetres per microsecond, and the echo covers the distance twice, there and back, so distance = duration × 0.034 ÷ 2. The result prints in centimetres twice a second. Select the sensor in the editor and change its distance in the properties panel to see the reading move.
Parts
- Arduino Uno
- Ultrasonic Sensor
Wiring
- Arduino Uno 5V → Ultrasonic Sensor VCC
- Arduino Uno D7 → Ultrasonic Sensor TRIG
- Ultrasonic Sensor ECHO → Arduino Uno D6
- Arduino Uno GND → Ultrasonic Sensor GND
Arduino code
// Ultrasonic Distance Meter
#define TRIG 7
#define ECHO 6
void setup() {
Serial.begin(9600);
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
}
void loop() {
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
// How long the echo pin stays HIGH is proportional to the distance.
long duration = pulseIn(ECHO, HIGH);
float distance = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.print(distance, 1);
Serial.println(" cm");
delay(500);
}
Try changing it
- Show inches too: after the existing print lines add Serial.println(distance / 2.54);
- Build a proximity warning: add pinMode(13, OUTPUT); in setup(), and in loop() add digitalWrite(13, distance < 20 ? HIGH : LOW); so the built-in LED lights when something is closer than 20 cm.