HC-SR04 ultrasonic sensor circuit diagram with Arduino Uno

How to Use the HC-SR04 Ultrasonic Sensor with Arduino Uno

In this guide, you will learn how to use the HC-SR04 ultrasonic sensor with Arduino Uno to measure distance, light an LED when an object comes close, and build the circuit on a breadboard without soldering.

Components Required

PartQuantityPurpose
HC-SR04 ultrasonic sensor1Measures distance using sound waves
Arduino Uno R3 DIP1Reads the sensor and runs the code
MB102 solderless breadboard, 830 points1Holds the sensor and LED without soldering
40-pin male-to-male jumper wires4Connects the sensor to the Uno
5 mm LED (any colour)1Lights up when an object is closer than 20 cm
220 ohm resistor1Protects the LED from too much current
USB cable (type A to B)1Powers the Uno and uploads the code

How the HC-SR04 Ultrasonic Sensor with Arduino Works

The HC-SR04 has two round “eyes” on its front. One is a transmitter and the other is a receiver. The transmitter is marked T and the receiver is marked R.

Here is what happens in one measurement. First, the Arduino sends a short 10-microsecond pulse to the Trig pin of the sensor. The sensor answers by sending out eight bursts of ultrasound at 40 kHz. Ultrasound is sound at a frequency too high for human ears, so you hear nothing. The sound travels through the air, hits an object, and bounces back. The receiver catches the echo, and the sensor holds its Echo pin HIGH for exactly as long as the sound was travelling.

The Arduino measures that HIGH time in microseconds. Distance is then simple maths. Sound travels at about 340 metres per second in air. The sound goes to the object and comes back, so it covers the distance twice. The sensor datasheet gives a ready-made formula: distance in centimetres equals the echo time in microseconds divided by 58.

Two details matter in real builds. First, the datasheet suggests waiting at least 60 milliseconds between measurements, so one echo does not mix with the next. Our code waits 200 milliseconds, which is safely above that. Second, sound needs a surface to bounce off. A flat, hard surface such as a wall or a book gives a clean echo. Soft cloth, foam or a surface tilted at a sharp angle scatters the sound, and the reading becomes unstable.

Key specifications of the HC-SR04:

SpecificationValue
Operating voltage5 V DC
Working current15 mA
Measuring range2 cm to 400 cm
Accuracyup to 3 mm
Measuring angle15 degrees
Sound frequency40 kHz
Trigger signal10 microsecond TTL pulse
Size45 x 20 x 15 mm

HC-SR04 Pinout and Wiring with Arduino Uno

The HC-SR04 has only four pins, which is why beginners like it. The table below shows every connection. There is no extra part between the sensor and the Uno. The sensor runs on 5 V, and the Uno gives it 5 V directly.

HC-SR04 pinArduino Uno pinWire colour used here
VCC5VRed
TrigD9Yellow
EchoD10Green
GNDGNDBlack

Connect the LED as well. Push the LED’s long leg (anode) into one row of the breadboard and the short leg (cathode) into another row. Connect a 220 ohm resistor from the short leg’s row to the Uno GND pin. Connect a jumper wire from the long leg’s row to Uno pin D13, which also drives the Uno’s built-in LED. That way both LEDs light together when an object comes close.

Before you power anything on, check two things. The sensor’s VCC must go to 5V, not 3.3V, or the readings will be wrong. And Trig and Echo must not be swapped. Swapped pins are the most common wiring mistake with this sensor, and the symptom is a reading of 0 cm that never changes.

HC-SR04 ultrasonic sensor circuit diagram with Arduino Uno
HC-SR04 circuit diagram with Arduino Uno — VCC to 5V, Trig to D9, Echo to D10, GND to GND, LED to D13.

Library Installation

No library is needed for this project. The code uses only two built-in Arduino functions, pulseIn() and millis(), so it works with a fresh Arduino IDE install.

If you later want shorter code, the NewPing library is a popular optional choice. Open the Library Manager with Sketch > Include Library > Manage Libraries, search for “NewPing”, and install it. This guide does not use it, because seeing the raw timing code teaches you how the sensor actually works.

Complete Arduino Code

/*
  HC-SR04 Ultrasonic Distance Meter with Arduino Uno
  Measures distance every 200 ms and prints it to the Serial Monitor.
  The LED on pin 13 lights up when an object is closer than 20 cm.
  No library needed. Formula from the HC-SR04 datasheet:
  distance in cm = echo time in microseconds / 58.
*/

const int TRIG_PIN = 9;   // HC-SR04 Trig pin
const int ECHO_PIN = 10;  // HC-SR04 Echo pin
const int LED_PIN  = 13;  // Built-in LED on the Uno

const int ALERT_DISTANCE_CM = 20;                 // LED turns on below this
const unsigned long MEASURE_INTERVAL_MS = 200;    // 5 readings per second
const unsigned long ECHO_TIMEOUT_US = 30000;      // about 500 cm max range

unsigned long lastMeasureTime = 0;

void setup() {
  Serial.begin(9600);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(TRIG_PIN, LOW);   // make sure Trig starts LOW
  Serial.println("HC-SR04 Distance Meter ready");
}

// Send one trigger pulse and return the distance in cm.
// Returns -1 when no echo is received within the timeout.
long measureDistanceCm() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);          // 10 us trigger pulse
  digitalWrite(TRIG_PIN, LOW);

  // pulseIn waits for the Echo pin to go HIGH, then times it.
  // The timeout stops it waiting forever when nothing is in range.
  unsigned long duration = pulseIn(ECHO_PIN, HIGH, ECHO_TIMEOUT_US);
  if (duration == 0) {
    return -1;
  }
  return duration / 58;           // datasheet formula
}

// Take 3 readings and return the middle one.
// This removes single odd readings caused by noise.
long medianDistanceCm() {
  long a = measureDistanceCm();
  long b = measureDistanceCm();
  long c = measureDistanceCm();

  // Simple sort of three values; the middle one is the median.
  if (a > b) { long t = a; a = b; b = t; }
  if (b > c) { long t = b; b = c; c = t; }
  if (a > b) { long t = a; a = b; b = t; }
  return b;
}

void loop() {
  unsigned long now = millis();

  // millis() timing: measure on a schedule, never with delay().
  if (now - lastMeasureTime >= MEASURE_INTERVAL_MS) {
    lastMeasureTime = now;

    long distance = medianDistanceCm();

    if (distance < 0) {
      Serial.println("No object in range");
      digitalWrite(LED_PIN, LOW);
    } else {
      Serial.print("Distance: ");
      Serial.print(distance);
      Serial.println(" cm");

      // LED on when something is closer than the alert distance.
      if (distance < ALERT_DISTANCE_CM) {
        digitalWrite(LED_PIN, HIGH);
      } else {
        digitalWrite(LED_PIN, LOW);
      }
    }
  }
}

Code Explanation

Pin and limit constants at the top. TRIG_PIN is 9 and ECHO_PIN is 10, matching the wiring table. ALERT_DISTANCE_CM is 20, so the LED lights up only for close objects. MEASURE_INTERVAL_MS is 200, which keeps the reading rate at five per second and stays well above the 60-millisecond gap the datasheet suggests. ECHO_TIMEOUT_US is 30000, which is about 500 cm of travel, beyond the sensor’s 400 cm limit.

setup() sets the pin directions. Trig is an OUTPUT because the Arduino drives it. Echo is an INPUT because the sensor drives it. The serial port starts at 9600 baud, which must match the baud rate you pick in the Serial Monitor.

measureDistanceCm() does one full measurement. It pulls Trig LOW, waits 2 microseconds, pulls it HIGH for exactly 10 microseconds, then LOW again. That 10-microsecond pulse is what tells the sensor to send its eight 40 kHz bursts. pulseIn(ECHO_PIN, HIGH, ECHO_TIMEOUT_US) then counts how long Echo stays HIGH. If nothing comes back, pulseIn() returns 0 after the timeout, and the function returns -1 as a clear “no object” signal. Otherwise it returns duration / 58, the datasheet formula.

medianDistanceCm() takes three readings and keeps the middle one. Sound readings sometimes jump for a single sample. A median filter removes those one-off jumps without slowing the output much. The three swaps sort the three values, and b ends up as the middle value.

loop() runs on a millis() schedule, not on delay(). It checks the clock, and only when 200 milliseconds have passed does it measure and print. The rest of the time the loop is free. That matters when you later add more parts, such as a servo or an LCD, because a delay() would freeze everything. Note one honest detail: pulseIn() itself waits for the echo, but never longer than 30 milliseconds, so the sketch stays responsive.

Demonstration: Expected Serial Monitor Output

If you have never uploaded code before, see our guide on how to upload code in Arduino Uno. Upload the code, then open the Serial Monitor with Tools > Serial Monitor and set the baud rate to 9600. Hold your hand about 25 cm in front of the sensor, then move it closer. You should see output like this:

HC-SR04 Distance Meter ready
Distance: 24 cm
Distance: 24 cm
Distance: 23 cm
Distance: 15 cm
Distance: 9 cm
No object in range
Distance: 31 cm

The LED lights up as soon as the reading drops below 20 cm and turns off again when you move your hand away. Move your hand past 400 cm and the monitor prints “No object in range”. If the numbers jump by one or two centimetres while your hand is still, that is normal. The sensor’s real-world repeatability is around a centimetre, even though the datasheet quotes 3 mm under ideal conditions.

Troubleshooting

  1. The monitor always shows “No object in range”. Check the wiring first. VCC must be on 5V and GND on GND. Make sure an object is actually in front of the sensor and within 400 cm. Also check that the sensor’s transmitter and receiver are facing the object, not the table or the ceiling.
  2. The reading is always 0 cm. Trig and Echo are almost certainly swapped. Swap the yellow and green wires back so Trig is on D9 and Echo is on D10. A reading of exactly 0 that never changes is the classic sign of this mistake.
  3. Readings jump around wildly. The surface may be soft, curved or tilted, which scatters the sound. Try a flat book or a wall held straight in front of the sensor. Check the power too. A weak USB port or a long, thin cable can make the 5 V line noisy. The median filter in the code already removes single jumps, so large jumps usually mean a real wiring or surface problem.
  4. It works at short range but fails past one metre. This is usually a power problem. The sensor draws 15 mA, which is small, but a poor USB cable or a laptop USB port in power-saving mode can still starve it. Try a different USB cable or a 5 V adapter into the Uno’s barrel jack. Keep the jumper wires short.
  5. The LED never lights up, even at 5 cm. Check the LED’s legs. The long leg must go towards pin D13 and the short leg towards GND through the 220 ohm resistor. An LED fitted backwards will not light. Also check ALERT_DISTANCE_CM in the code. If you set it to 5, the LED only lights under 5 cm.
  6. The code uploads, but the Serial Monitor stays empty. Check the baud rate in the Serial Monitor. It must be 9600, the same as Serial.begin(9600). Also check that you selected the right board (Arduino Uno) and the right COM port under Tools. If the upload itself fails, try a different USB cable. Some cheap cables are charge-only and carry no data.

Project Ideas and FYP Ideas Using the HC-SR04

  1. Smart parking assistant. Mount the sensor at the back of a car parking bay. When a car comes within 30 cm of the wall, a buzzer beeps faster as the distance falls. It is the same idea as a real car parking sensor, built from one module.
  2. Water tank level indicator. Fix the sensor above a water tank, pointing down at the water surface. The distance reading tells you the water level. Add three LEDs for empty, half and full, or an LCD that shows the level in percent.
  3. Blind stick. Fit the sensor on a walking stick with a buzzer. When an obstacle is closer than 50 cm, the buzzer warns the user. It is a strong final year project because it solves a real problem and is easy to demonstrate.
  4. Automatic hand sanitiser dispenser. Put the sensor above a small pump. When a hand comes within 10 cm, the Arduino runs the pump for one second. This was a popular student project because the wiring is simple and the demo is instant.
  5. Obstacle-avoiding robot car. Put the sensor on a servo at the front of a robot car. The car drives forward, scans left and right when it sees an obstacle, and turns towards the open side. Pair it with an L298N motor driver and a 4WD chassis for a full FYP.

Still stuck?

If the build does not work, message us on WhatsApp and we will help:

You can also watch our videos on YouTube:

Frequently Asked Questions

What is the maximum range of the HC-SR04 ultrasonic sensor?

The datasheet range is 2 cm to 400 cm. In practice, reliable readings stop around 300 to 350 cm, because the echo gets weak. For anything further away, use a different sensor such as a laser rangefinder.

Can the HC-SR04 work with 3.3 V boards like the ESP32?

Not directly. The sensor needs 5 V power, and its Echo pin returns a 5 V signal, which can damage a 3.3 V board. Use a voltage divider on the Echo line, for example a 1k resistor in series and a 2k resistor to ground, so the board only sees about 3.3 V. [VERIFY] The exact trigger threshold voltage is not stated in the datasheet, so test the Trig line from 3.3 V before relying on it.

Why does my HC-SR04 show a wrong distance in hot or cold weather?

The speed of sound changes with temperature, about 0.6 metres per second for each degree Celsius. The code assumes 340 metres per second. On a very hot day the real speed is higher, so distances read slightly long. For most student projects the error is small enough to ignore.

How accurate is the HC-SR04?

The datasheet quotes accuracy up to 3 mm under ideal conditions. In a normal room, expect about 1 cm of error. The main causes are temperature, the surface material and the angle of the object.

What is the HC-SR04 ultrasonic sensor price in Pakistan?

The HC-SR04 costs Rs 200 at QKZee Technologies. You also need an Arduino Uno, a breadboard and jumper wires, which brings a complete starter setup to roughly Rs 1,800.

Conclusion

The HC-SR04 ultrasonic sensor with Arduino is a small build with a big payoff. You have wired a sensor, timed a sound echo, turned microseconds into centimetres, and added a working alert. The same three ideas, trigger, echo and timing, appear again in parking sensors, tank alarms and robot cars. Try the water tank or blind stick idea next. It uses the same code you just wrote, with only a few lines changed.

Components for this project are available at QKZee Technologies, and smart circuit hub with nationwide Cash on Delivery across Pakistan.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *