Preview build — page text is a draft awaiting human review. Code badges come from real compiles. The flasher is real but not yet hardware-tested; the Playground is still a preview.

HC-SR04 with Arduino Uno — ultrasonic distance wiring and code

Wire an HC-SR04 ultrasonic sensor to an Arduino Uno on D7/D8 — no divider needed at 5 V — and print distance in centimetres.

Arduino C++Verified — core avr 1.8.8, 3 Nov 2026Compile-only

Community draft — report a mistake

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 R3Only the pins used are shown · 5 V logicHC-SR04 ultrasonic sensor5VGNDD7D8VCCTrigEchoGND
Every connection
Arduino Uno R3HC-SR04 ultrasonic sensorWireNotes
5VVCCred
D7Triggreen
D8Echoblue
GNDGNDblack

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-uno.inoArduino C++Open in PlaygroundOpen in PlaygroundFlash
// 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

Serial Monitor · 9600Output
Distance: 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.

↑↓ to move · Enter to open