Anu Electronics HC-SR04 distance-sensor tutorial cover with a blue ultrasonic module and Arduino Circuit, Wiring and Code subtitle.

HC-SR04 with Arduino Uno: Distance Measurement, Circuit, Wiring and Code

Draft review note: Code is complete and copyable; hosted code download is pending because file-transfer access is restricted. The store identifies HC-SR04 and lists 5 V / 15 mA, but does not identify the PCB manufacturer. Confirm the delivered board labels and revision against the reference before approval. No physical test or Arduino compilation has been performed.

Use the HC-SR04 ultrasonic sensor with an Arduino Uno R3 to display distance in Serial Monitor and turn on the built-in LED when a flat target moves close. This original tutorial includes four-wire connections, a complete sketch and a test plan that distinguishes missing echoes from valid readings.

What you will build

A USB-powered tabletop distance indicator. The LED turns on below 20 cm and turns off above 25 cm. Between those points it keeps its previous state, reducing flicker. Use a large flat cardboard panel or a wall as the target. This is an educational demonstration, not a safety or collision-prevention device.

Contents

  1. How it works
  2. Components
  3. Circuit and visual wiring
  4. Assembly and IDE setup
  5. Complete Arduino code
  6. Upload and test
  7. Troubleshooting and FAQs

How it works

The sensor sends ultrasonic sound after a trigger pulse. Echo pulse width represents the outgoing and returning travel time. The sketch estimates one-way distance with distanceCm = durationUs × 0.0343 / 2, using an approximate room-temperature speed of sound. For example, 2,000 microseconds gives 34.3 cm; this is a calculation example, not a measurement.

A temperature change, an angled target, fabric or a small object can affect the result. One decimal place in the display does not establish 0.1 cm accuracy. The program pauses 100 ms after each attempt so repeated pings do not crowd each other.

Parts and purchase links

Component Needed Specification / pack size
HC-SR04 ultrasonic sensor 1 ANU-HC-SR04; 5 V, listed operating current 15 mA; one module.
Arduino Uno R3 1 5 V ATmega328P board with built-in LED and USB-B connector.
Male-to-female jumper wires 4 leads 20 cm; sold as a pack of 40. Female ends fit sensor header, male ends fit Uno sockets.
USB A-to-B data cable 1 USB-B at Uno; USB-A at computer. A computer adapter may be needed.

Also have a computer, a ruler and a large flat target ready. No breadboard, separate LED or external LED resistor is needed: the sensor connects through fitted headers and the sketch uses the Uno built-in LED.

Pinout and connection table

HC-SR04 label Uno connection Role
VCC 5V Sensor power
GND GND Shared ground
TRIG D9 Trigger output from Uno
ECHO D10 Pulse input to Uno

Circuit schematic

HC-SR04 to Uno schematic: VCC to 5V, GND to GND, TRIG to D9, ECHO to D10.
HC-SR04 to Uno schematic: VCC to 5V, GND to GND, TRIG to D9, ECHO to D10.

Visual module wiring

Symbolic HC-SR04 visual wiring; follow printed labels rather than illustrated pin positions.
Symbolic HC-SR04 visual wiring; follow printed labels rather than illustrated pin positions.

The drawings are symbolic: follow the printed pin labels, not the illustrated positions. In the store front photo the header labels read VCC, TRIG, ECHO, GND with pins pointing down. Verify your actual board before connecting. These diagrams show the module interface rather than its internal circuitry.

Echo uses 5 V logic. Direct wiring here is appropriate for the 5 V Uno R3; do not connect Echo directly to an ESP32 or another 3.3 V-only input. Disconnect USB before rewiring. Power the sensor from 5V, not from a GPIO or VIN, and check for reversed VCC/GND.

Assembly and Arduino IDE setup

  1. Check that the module is labelled HC-SR04 and has the four stated pins. Disconnect all power.
  2. Connect GND, VCC, TRIG and ECHO using the table. Keep leads short and secure. Place the sensor facing the target, away from tabletop edges that could reflect sound.
  3. Connect the Uno through its USB data cable. USB provides power for this single-sensor setup.
  4. Install Arduino IDE from the official Arduino website. In Boards Manager install Arduino AVR Boards if needed; select Arduino Uno and its port.
  5. Create a sketch named uno_hcsr04_distance. Paste the program below. No additional library or cloud setup is needed.

Complete Arduino code

Copy this complete sketch into Arduino IDE. The downloadable file is pending upload.

// Original Anu Electronics HC-SR04 + Arduino Uno R3 tutorial.
// VCC -> 5V, GND -> GND, TRIG -> D9, ECHO -> D10.
// Direct ECHO wiring is for the 5V Uno, not an ESP32.
const byte TRIG_PIN = 9;
const byte ECHO_PIN = 10;
const unsigned long ECHO_TIMEOUT_US = 30000UL;
bool nearObject = false;

void setup() {
  pinMode(TRIG_PIN, OUTPUT);
  digitalWrite(TRIG_PIN, LOW);
  pinMode(ECHO_PIN, INPUT);
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);
  Serial.begin(9600);
  delay(100);
}

void loop() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  unsigned long duration = pulseIn(ECHO_PIN, HIGH, ECHO_TIMEOUT_US);
  if (duration == 0) {
    nearObject = false;
    digitalWrite(LED_BUILTIN, LOW);
    Serial.println(F("NO ECHO | status unknown"));
  } else {
    float distanceCm = duration * 0.0343f / 2.0f;
    if (distanceCm < 2.0f || distanceCm > 400.0f) {
      nearObject = false;
      digitalWrite(LED_BUILTIN, LOW);
      Serial.println(F("OUT OF RANGE | status unknown"));
    } else {
      if (distanceCm < 20.0f) nearObject = true;
      if (distanceCm > 25.0f) nearObject = false;
      digitalWrite(LED_BUILTIN, nearObject ? HIGH : LOW);
      Serial.print(F("Distance: "));
      Serial.print(distanceCm, 1);
      Serial.println(nearObject ? F(" cm | NEAR") : F(" cm | CLEAR"));
    }
  }
  delay(100); // More than 60 ms between triggers, including after failure.
}

Key code sections

  • D9 sends a 10 microsecond trigger. D10 remains an input and measures Echo.
  • pulseIn has a 30,000 microsecond timeout. A zero return prints NO ECHO instead of 0 cm.
  • Calculated readings outside 2–400 cm are rejected. A value within that band can still be wrong if the target is unsuitable.
  • Thresholds at 20 cm and 25 cm provide hysteresis. At exactly either threshold the previous state is retained.
  • On invalid readings, the LED switches off and the program reports an unknown state. An unlit LED alone does not prove the path is clear.

Upload and test

  1. Click Verify, then Upload. Open Serial Monitor at 9600 baud.
  2. Place a broad flat target roughly 40 cm from the transducer faces and perpendicular to the sensor. Compare the displayed estimate with a ruler.
  3. Move it near 18 cm. Expect NEAR and an illuminated built-in LED. Move toward 23 cm: the LED should remain on.
  4. Move beyond 25 cm, such as 28 cm. Expect CLEAR and the LED off. Approach 23 cm again: it should remain off until below 20 cm.
  5. Point the sensor toward an open area with no useful reflector. If no pulse is received within the timeout, expect NO ECHO. Other reflections can still produce a reading.
  6. Repeat at several distances. Record actual results separately; do not treat the animation as a measured calibration.

Expected output animation

Simulated distance and LED-state sequence, including no-echo handling; not measured results.
Simulated distance and LED-state sequence, including no-echo handling; not measured results.

Illustrative values only. The animation demonstrates the program branches and has no physical sensor recording.

Troubleshooting

Symptom What to check
Repeated NO ECHO Check 5V, common ground, TRIG D9 and ECHO D10. Use a large flat target and inspect connectors.
Jumping readings Remove nearby reflectors, hold the target still and face it squarely. Soft, curved or angled surfaces may return weak echoes.
OUT OF RANGE Move the target away from the near blind region and into a practical test distance. Check that the correct Echo pin is used.
Cannot upload Choose Uno and its port, use a data cable and close other programs that have opened the serial port.
Sensor stops responding Disconnect power, inspect the wiring and reconnect. Do not keep using a module that behaves inconsistently.

FAQs

Does it work at every distance up to 4 m?

No. That is a listed range under suitable conditions. Target shape, size, material, orientation and the environment matter.

Is the detection angle 15° or 30°?

The reference datasheet and store listing use different angle figures. Do not design around an assumed cone; verify coverage with the supplied revision and real targets.

Can I use two sensors together?

Trigger them separately and leave time for echoes to decay. Simultaneous pings can cause interference; this sketch is for one sensor.

Can it measure water level outdoors?

This exposed module is not presented as waterproof. A protected, application-appropriate sensor and installation are needed for that use.

Related tutorials and parts

For another input project, try the Arduino LDR light-sensor tutorial. To learn a different way to read an input, see the push-button counter tutorial.

Get the HC-SR04 sensor and Uno R3, with the compatible wires and USB cable linked above.

Technical sources and testing limits

Original writing, sketch and diagrams; CircuitDigest informed the tutorial structure only. Product imagery is based on the store photo. The reference specifies 5 V, 15 mA, a trigger of at least 10 microseconds and more than 60 ms between measurement cycles. The store manufacturer/revision is unspecified, so matching reference specifications do not establish manufacturer identity. Code logic has been checked with simulated inputs; Arduino compilation and hardware testing remain pending.