The HC-SR04 measures distance by timing an ultrasonic ping. On the Uno it is the easiest version of this project: both sides run at 5 V, so it is four wires and no extra parts.
The sketch fires a 10 µs trigger pulse, times the echo and converts it to centimetres using the speed of sound (0.0343 cm/µs, halved for the round trip).
Wiring
| Arduino Uno R3 | HC-SR04 ultrasonic sensor | Wire | Notes |
|---|---|---|---|
| 5V | VCC | red | |
| D7 | Trig | green | |
| D8 | Echo | blue | |
| GND | GND | black |
5 V (HC-SR04P / RCWL-1601: 3–5.5 V) part, 5 V board. The classic HC-SR04 needs 5 V and its ECHO pin outputs 5 V. On a 3.3 V board (ESP32, Pico) send ECHO through a 1 kΩ / 2 kΩ divider. A 3.3 V trigger signal is enough for TRIG.
Board quirks
- The Uno and the HC-SR04 are both 5 V, so Echo goes straight into D8 — no divider, unlike on an ESP32.
pulseIn()with a 30 ms timeout limits the range to about 5 m and stops the sketch hanging when nothing echoes back.- Readings below 2 cm and beyond about 4 m are unreliable; soft surfaces absorb the ping.
Code
// HC-SR04 ultrasonic distance sensor on an Arduino Uno R3.
// VCC → 5V, Trig → D7, Echo → D8, GND → GND. Both run at 5 V, so no divider is needed.
const uint8_t TRIG_PIN = 7;
const uint8_t ECHO_PIN = 8;
void setup() {
Serial.begin(9600);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
digitalWrite(TRIG_PIN, LOW);
}
void loop() {
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
unsigned long us = pulseIn(ECHO_PIN, HIGH, 30000UL); // ~5 m max
if (us == 0) {
Serial.println(F("Out of range or no echo"));
} else {
Serial.print(F("Distance: "));
Serial.print(us * 0.0343 / 2.0, 1);
Serial.println(F(" cm"));
}
delay(200);
}// HC-SR04 ultrasonic distance sensor on an Arduino Uno R3.
// VCC → 5V, Trig → D7, Echo → D8, GND → GND. Both run at 5 V, so no divider is needed.
const uint8_t TRIG_PIN = 7;
const uint8_t ECHO_PIN = 8;
void setup() {
Serial.begin(9600);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
digitalWrite(TRIG_PIN, LOW);
}
void loop() {
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
unsigned long us = pulseIn(ECHO_PIN, HIGH, 30000UL); // ~5 m max
if (us == 0) {
Serial.println(F("Out of range or no echo"));
} else {
Serial.print(F("Distance: "));
Serial.print(us * 0.0343 / 2.0, 1);
Serial.println(F(" cm"));
}
delay(200);
}Expected serial output
Distance: 23.4 cm
Distance: 23.5 cm
Out of range or no echoDistance: 23.4 cm Distance: 23.5 cm Out of range or no echo
Common errors
Always 0 or “no echo”
Trig and Echo swapped, or the module has no 5 V. Full fix.
Values jump around
Mount the sensor firmly and aim it square at a hard surface; average several readings.