Arduino Ultrasonic Sensor (HC-SR04) Distance Code
hardSensorsArduino (C++)
The HC-SR04 sends a sound pulse and times the echo — from that time we calculate the distance.
The question
An HC-SR04 has TRIG on pin 11 and ECHO on pin 3. Measure the distance in centimetres (distance = duration × 0.034 / 2) and print it to the Serial Monitor at 9600 baud every 200 ms.
The sketch
sketch.ino
void setup() {
Serial.begin(9600);
pinMode(11, OUTPUT);
pinMode(3, INPUT);
}
void loop() {
digitalWrite(11, LOW);
delayMicroseconds(2);
digitalWrite(11, HIGH);
delayMicroseconds(10);
digitalWrite(11, LOW);
long duration = pulseIn(3, HIGH);
float cm = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.print(cm);
Serial.println(" cm");
delay(200);
}Wiring
HC-SR04: VCC → 5V, GND → GND, TRIG → pin 11, ECHO → pin 3.
How it works
- 1A 10-microsecond HIGH pulse on TRIG starts one measurement.
- 2pulseIn(ECHO, HIGH) returns how long the echo took, in microseconds.
- 3Sound travels about 0.034 cm per microsecond; the pulse goes there and back, so divide by 2.
Common mistakes
- Setting ECHO as OUTPUT — it must be INPUT.
- Forgetting to divide by 2, which doubles every distance.
Now solve a similar question yourself
A new Arduino question every time, checked instantly.
