Measure Distance with HC-SR04 (Arduino)
Measure distance with an ultrasonic sensor and print centimeters to the Serial Monitor.
Beginner20 min
What you need
Wiring
Hover a pin or a wire to trace the connection.
Code
ultrasonic.ino
// Measure distance with an HC-SR04 ultrasonic sensor.
const int trigPin = 9;
const int echoPin = 10;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(trigPin, LOW); delayMicroseconds(2);
digitalWrite(trigPin, HIGH); delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long us = pulseIn(echoPin, HIGH); // echo pulse width
long cm = us / 58; // ~58 us per cm (round trip)
Serial.print(cm); Serial.println(" cm");
delay(300);
}
Steps
- Wire the sensor: VCC to 5V, GND to GND, Trig to D9, Echo to D10.
- Upload and open the Serial Monitor at 9600 baud.
- Move your hand toward and away from the sensor to see the distance change.