HC-SR04 guides · On this page

Measure Distance with an HC-SR04 on an Arduino

Measure distance with an HC-SR04 on an Arduino, running in your browser before you build it. The HC-SR04 sends a short burst of ultrasound and times its echo, so it measures from 2 cm to 400 cm without touching anything. It needs 5 V, and a large, flat, smooth target reads best.

Left to right: a blue HC-SR04 with two silver transducers marked T and R, a crystal between them and four pins labelled VCC, Trig, Echo, Gnd; a green RCWL-1601 with the same two transducers and four pins; and a green US-100 with a crystal and five pins labelled VCC, Trig/Tx, Echo/Rx, GND, GND.
HC-SR04Blue, 5 V: this guideRCWL-16013 V or 5 V, same codeUS-1005 pins; jumper off

Try it first, no parts needed

This is the whole project, wired and running in your browser. Press Run simulation, then move the target with the slider, or hold the button to bring your hand close, and watch the Uno print each distance. Here the target never leaves the beam, so you won't see Out of range.

Ready
Open in Cirkit Designer

What the HC-SR04 sees

The sketch takes a reading, then waits 100 ms.

100 cm

Arduino Uno serial monitor115200 baud

Output appears here when the simulation runs.

What the code does

The sketch starts a reading, times the echo, turns the time into centimetres and prints it, then waits 100 ms and starts again.

hc_sr04_distance.ino
// Measure distance with an HC-SR04. A 10 us pulse on TRIG
// starts a reading; ECHO then stays HIGH for 58 us per cm.
const int TRIG_PIN = 10;
const int ECHO_PIN = 9;

void setup() {
  Serial.begin(115200);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
}

void loop() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);  // a 10 us pulse starts it
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  // Wait up to 30 ms: 400 cm takes about 23 ms.
  unsigned long echoUs = pulseIn(ECHO_PIN, HIGH, 30000);
  if (echoUs == 0) {
    Serial.println("Out of range");
  } else {
    float cm = echoUs / 58.0;  // 58 us of echo per cm
    Serial.print("Distance: ");
    Serial.print(cm, 1);       // one decimal place
    Serial.println(" cm");
  }
  delay(100);  // at least 60 ms between readings
}
  1. const int TRIG_PIN = 10;

    TRIG on pin 10 and ECHO on pin 9, right under the sensor in the picture. Other digital pins work too; change these two numbers to match.

  2. digitalWrite(TRIG_PIN, HIGH);  // a 10 us pulse starts it

    Holds TRIG HIGH for 10 µs, the start signal the datasheet asks for, after a brief LOW so each pulse starts from LOW.

  3. unsigned long echoUs = pulseIn(ECHO_PIN, HIGH, 30000);

    Waits for ECHO to go HIGH and times how long it stays HIGH, in microseconds. If nothing comes back within 30 ms, it gives 0. See how a reading works.

  4. float cm = echoUs / 58.0;  // 58 us of echo per cm

    Turns the time into centimetres: the datasheet's 58 µs for each centimetre to the target, there and back.

  5. delay(100);  // at least 60 ms between readings

    Waits 100 ms before the next reading; the datasheet asks for more than 60 ms between readings, so a new burst doesn't start while the last one's echo is still about.

Want inches? Divide by 148 instead; see the FAQ.

Build it on an Arduino

Now with real parts. Check which pin is which, wire it, get the code, then upload it and watch the distances. Using an ESP32 board? It has its own guide →

Which pin is which: the HC-SR04 pinout

With the two round transducers facing you, the pins along the bottom edge are, left to right, VCC, TRIG, ECHO and GND. The labels are printed beside them.

HC-SR04 pinout with the transducers facing you, left to right along the bottom edge: 1 VCC, 5 V, to 5V on an Uno; 2 TRIG, a HIGH of at least 10 microseconds starts a reading, to pin 10; 3 ECHO, HIGH for 58 microseconds per centimetre, to pin 9; 4 GND, to GND. The transducer marked T sends the sound and the one marked R hears it.
MeasuresDistance, 2 cm to 400 cm, with ultrasound
Supply5 V, 15 mA
PinsVCC, TRIG, ECHO, GND
BeamA 15° measuring angle
The echoECHO stays HIGH 58 µs for each centimetre
ReadingsMore than 60 ms apart
LibraryNone: pulseIn() is built in

You'll need

  • An Arduino Uno and its USB cable
  • An HC-SR04
  • Four jumper wires, female to male if they go straight onto the sensor's pins
  • Software to upload the sketch to the Uno: either Cirkit Designer, free in your browser, or the Arduino IDE, a free download for Windows, macOS and Linux
  1. Wire it

    Four wires, each from one of the sensor's pins straight to the Uno.

    Tap a connection to see it on the circuit.

    HC-SR04 pinConnect to the UnoShow
    VCC5VShow
    TRIGPin 10Show
    ECHOPin 9Show
    GNDGNDShow

    Connect GND first if the Uno is already powered, as the datasheet asks; otherwise the module may not work properly.

  2. Get the code

    I'm using:

    Steps 2 and 3 follow the tool you pick.

    Open in Cirkit Designer

    The project opens with the sketch already in it, so there's nothing to install.

    No Arduino IDE yet? Download it free for Windows, macOS or Linux.

    The sketch needs no library. Copy it into a new sketch:

    How it works line by line is in what the code does, above.

  3. Upload and check it

    Plug in your Uno. In Cirkit, open the Build tab, then Upload firmware: click Select Port and pick your Uno, then Upload to Device. The first time, Cirkit asks you to install Cirkit Create Agent, a small desktop helper that lets it reach the board over USB. Then open Upload output and serial monitor and click Start Serial Monitor.

    Show me where to click in Cirkit
    HC-SR04 on an Arduino UnoFileEditExportHelp
    DesignCodeSimulateBuild
    1Parts & purchasing2Assemble3Upload firmware
    Arduino UnoEdit Code

    Board

    Arduino Uno Change

    2

    Port

    Select PortCOM3 Connected

    3

    Upload

    Upload to DeviceUploading...Upload successful

    4

    Check that it works

    Your project should now run as designed.

    Upload output and serial monitor
    Compile / Upload Output
    Sketch uses 3884 bytes (12%) of program storage space. Maximum is 32256 bytes.
    Global variables use 228 bytes (11%) of dynamic memory, leaving 1820 bytes for local variables. Maximum is 2048 bytes.
    Device SerialStop

    Read serial data from your device.

    Start Serial Monitor
    Listening on COM3 at 115200 baud
    Distance: 99.4 cm
    Distance: 99.5 cm
    Distance: 99.4 cm
    Distance: 24.9 cm
    Distance: 24.8 cm
    Select port

    Select a device port

    Select the device port for uploading code and serial communications

    COM3 (Arduino Uno)
    1. Open Build
    2. Choose Upload firmware
    3. Click Select Port
    4. Pick COM3 (Arduino Uno)
    5. Click Upload to Device
    6. Open Upload output and serial monitor
    7. Click Start Serial Monitor

    In the Arduino IDE, choose Arduino Uno and its port from the board menu, press Upload, then open the Serial Monitor and set it to 115200 baud.

    Show me where to click in the Arduino IDE
    Select BoardArduino Uno

    Select other board and port

    Arduino UnoCOM3
    hc_sr04_distance.ino
    // Measure distance with an HC-SR04. A 10 us pulse on TRIG
    // starts a reading; ECHO then stays HIGH for 58 us per cm.
    const int TRIG_PIN = 10;
    const int ECHO_PIN = 9;
    
    void setup() {
    OutputSerial Monitor115200 baud

    Compiling sketch...

    Sketch uses 3884 bytes (12%) of program storage space. Maximum is 32256 bytes.

    Global variables use 228 bytes (11%) of dynamic memory, leaving 1820 bytes for local variables. Maximum is 2048 bytes.

    Uploading...

    Distance: 99.4 cm

    Distance: 99.5 cm

    Distance: 99.4 cm

    Distance: 24.9 cm

    Distance: 24.8 cm

    Done uploading.

    1. Click the board menu
    2. Pick Arduino Uno on COM3
    3. Click Upload
    4. Wait for Done uploading
    5. Click Serial Monitor
    6. Check it is set to 115200 baud

    It works when:

    • A new distance appears several times a second, such as Distance: 99.4 cm with something about a metre away.
    • You move your hand towards the sensor and the distance drops with it.
    • With nothing in front within 400 cm, it prints Out of range.

    Not working? If it only ever prints Out of range, see troubleshooting.

    Next guideNext: build a parking sensorThe same sensor and an LED that blinks faster as something gets closer.

Troubleshooting

Find your symptom; the checks under it run from the most common cause down.

It always prints "Out of range"

No echo reached ECHO within 30 ms. Check, in order:

  • TRIG and ECHO aren't swapped. TRIG goes to the pin the sketch drives (10), ECHO to the pin it reads (9).
  • VCC is on 5V. The HC-SR04 needs 5 V, so 3V3 isn't enough.
  • Something is in front, within 400 cm, big and flat enough; see accuracy and limits.

The distance jumps about

  • The target is big, flat and smooth. See accuracy and limits.
  • Nothing else sits in the beam. The datasheet's measuring angle is 15°, so an object off to one side can be what it measures.
  • Readings are more than 60 ms apart. The datasheet asks for that, so a new burst doesn't start while the last echo is still about.

Nothing in the Serial Monitor, or garbled characters

  • The Serial Monitor is set to 115200 baud. It must match Serial.begin(115200) in the sketch.

How a reading works

The HC-SR04 measures distance by timing sound. When TRIG goes HIGH for 10 µs, the transducer marked T sends eight cycles of ultrasound at 40 kHz. Once the burst has gone out, ECHO goes HIGH and stays HIGH until R hears it come back, so the time ECHO is HIGH is the time the sound took to reach the target and return.

How a reading works: the HC-SR04 sends ultrasound from T to a target and it comes back to R. The timing: TRIG HIGH for 10 microseconds, a burst of eight cycles at 40 kHz, then ECHO HIGH until the echo returns, 58 microseconds for each centimetre to the target.

The datasheet gives two ways to turn the time into distance. Its rule of thumb is microseconds ÷ 58 for centimetres (÷ 148 for inches), which is what the sketch uses. Its other formula takes sound at 340 m/s, which works out to ÷ 58.8. The two differ by about 1 %: ÷ 58 matches sound at about 345 m/s, the speed in air at about 23 °C.

The echo, timedExample: a target at 100 cmRun the circuit at the top, and this shows the echo for the distance you set.

TRIG: 10 µs starts it (drawn wider, to see)

ECHO: HIGH from the end of the burst until the sound comes back

0 ms5 ms10 ms15 ms20 ms25 ms

Accuracy and limits

HC-SR04
Range2 cm to 400 cm
Best caseThe datasheet says its ranging accuracy "can reach" 3 mm; it gives no conditions
BeamA 15° measuring angle; an object anywhere in it can be what it measures
TargetAt least 0.5 m², as flat and smooth as you can
TemperatureSound is slower in cold air: at 0 °C (331 m/s) the sketch's ÷ 58 reads about 4 % long, at 30 °C (349 m/s) about 1 % short
RateReadings more than 60 ms apart

pulseIn() can add a small error of its own: Arduino notes its timing may be off on longer pulses. For readings to the centimetre, check a few known distances on your own board with a tape measure and adjust the sketch's 58 to match.

HC-SR04 or something else?

How it measuresRangeInterfaceChoose it for
HC-SR04Ultrasound, 15° beam2 to 400 cmTwo digital pins, 5 VThe longest range of these, on two pins with no library
Sharp GP2Y0A21YK0FInfrared, by triangulation10 to 80 cmOne analog pin, 4.5 to 5.5 VShort range on one pin; the target's colour hardly changes the reading
ST VL53L0XLaser time of flight, 25° field of viewUp to 1.2 m by default, 2 m on a white target in the darkI²CA 3.3 V board or a shared I²C bus, up to about 1.2 m

HC-SR04 FAQ

How far can an HC-SR04 measure?

From 2 cm to 400 cm, by its datasheet, on a large, flat target.

How do I get inches?

Divide the echo time by 148 instead of 58, the datasheet's figure for inches:

In loop(), in place of the four lines that work out and print centimetres
float inches = echoUs / 148.0;  // 148 us of echo per inch
Serial.print("Distance: ");
Serial.print(inches, 1);
Serial.println(" in");
Does the HC-SR04 work at 3.3 V?

No, it needs 5 V. On a 3.3 V board such as an ESP32, power it from the board's 5V pin and bring ECHO down with a voltage divider; the ESP32 guide shows how.

Why does the sketch wait 100 ms between readings?

The datasheet asks for more than 60 ms between readings, so a new burst doesn't start while the last one's echo is still about. Waiting 100 ms after each reading leaves plenty.

My sensor has five pins and says US-100. Does this work?

Yes, with the jumper on its back removed: then it works like an HC-SR04, with a trigger and an echo pin, and this sketch runs unchanged. With the jumper in place it talks UART at 9600 baud instead. It runs on 2.4 V to 5.5 V.

My sensor is green and says RCWL-1601. Does this work?

Yes. It is HC-SR04 compatible, so this sketch and wiring work unchanged, and it also runs on 3 V, so on an ESP32 it can be powered from 3V3 without the divider.

Do I need a library?

No. pulseIn() is built into Arduino, and the sketch's 58 does the rest.

Simulating the HC-SR04 in Cirkit Designer

Cirkit's HC-SR04 answers the sketch through the Uno's real pins: a TRIG pulse of at least 10 µs starts a reading, and ECHO goes HIGH about 200 µs later for the distance × 58 µs, from 2 to 400 cm. With no target, it sends no pulse. It needs 4.5 to 5.5 V between VCC and GND, and it is tested on the Arduino Uno, the ESP32-S3 and the classic ESP32.

Its echo is exact, with no beam, surface, temperature or noise. Readings still come out a little short at long range (a target at 100 cm prints about 99.4 cm), and the last digit moves by one from reading to reading, aspulseIn()'s timing lands.

References