Complete Guide for Ultrasonic Sensor HC-SR04 with Arduino

This article is a guide about the Ultrasonic Sensor HC-SR04. We’ll explain how it works, show you some of its features and share an Arduino project example you can follow to integrate into your projects. We provide a schematic diagram on how to wire the ultrasonic sensor and an example sketch with the Arduino.

Complete Guide for Ultrasonic Sensor HC-SR04 with Arduino

Description

The HC-SR04 ultrasonic sensor uses sonar to determine the distance to an object. This sensor reads from 2cm to 400cm (0.8inch to 157inch) with an accuracy of 0.3cm (0.1inches), which is good for most hobbyist projects. In addition, this particular module comes with ultrasonic transmitter and receiver modules.

The following picture shows the HC-SR04 ultrasonic sensor.

HC-SR04 Ultrasonic Sensor Module Distance Measurement Component Part Front

The next picture shows the other side of the sensor.

HC-SR04 Ultrasonic Sensor Module Distance Measurement Component Part Back

Features

Here’s a list of some of the HC-SR04 ultrasonic sensor features and specs—for more information, you should consult the sensor’s datasheet:

  • Power Supply :+5V DC
  • Quiescent Current : <2mA
  • Working Current: 15mA
  • Effectual Angle: <15°
  • Ranging Distance : 2cm – 400 cm/1″ – 13ft
  • Resolution : 0.3 cm
  • Measuring Angle: 30 degree
  • Trigger Input Pulse width: 10uS TTL pulse
  • Echo Output Signal: TTL pulse proportional to the distance range
  • Dimension: 45mm x 20mm x 15mm

How Does it Work?

The ultrasonic sensor uses sonar to determine the distance to an object. Here’s what happens:

  1. The ultrasound transmitter (trig pin) emits a high-frequency sound (40 kHz).
  2. The sound travels through the air. If it finds an object, it bounces back to the module.
  3. The ultrasound receiver (echo pin) receives the reflected sound (echo).
How Ultrasonic Sensor Works

The time between the transmission and reception of the signal allows us to calculate the distance to an object. This is possible because we know the sound’s velocity in the air. Here’s the formula:

distance to an object = ((speed of sound in the air)*time)/2
  • speed of sound in the air at 20ºC (68ºF) = 343m/s

HC-SR04 Ultrasonic Sensor Pinout

ultra

Here’s the pinout of the HC-SR04 Ultrasonic Sensor.

VCCPowers the sensor (5V)
TrigTrigger Input Pin
EchoEcho Output Pin
GNDCommon GND

Where to buy?

You can check the Ultrasonic Sensor HC-SR04 sensor on Maker Advisor to find the best price:

Arduino with HC-SR04 Sensor

Arduino UNO Board HC-SR04 Ultrasonic Sensor Module Arduino

This sensor is very popular among Arduino tinkerers. So, here we provide an example of how to use the HC-SR04 ultrasonic sensor with the Arduino. In this project, the ultrasonic sensor reads and writes the distance to an object in the serial monitor.

The goal of this project is to help you understand how this sensor works. Then, you should be able to use this example in your own projects.

Parts Required

Here’s a list of the parts required to follow the next tutorial:

You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!

Arduino with HC-SR04 Sensor Wiring

Follow the next schematic diagram to wire the HC-SR04 ultrasonic sensor to the Arduino.

The following table shows the connections you need to make:

Ultrasonic Sensor HC-SR04Arduino
VCC5V
TrigPin 11
EchoPin 12
GNDGND

Code

Upload the following code to your Arduino IDE.

/*
 * created by Rui Santos, https://randomnerdtutorials.com
 * 
 * Complete Guide for Ultrasonic Sensor HC-SR04
 *
    Ultrasonic sensor Pins:
        VCC: +5VDC
        Trig : Trigger (INPUT) - Pin11
        Echo: Echo (OUTPUT) - Pin 12
        GND: GND
 */
 
int trigPin = 11;    // Trigger
int echoPin = 12;    // Echo
long duration, cm, inches;
 
void setup() {
  //Serial Port begin
  Serial.begin (9600);
  //Define inputs and outputs
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}
 
void loop() {
  // The sensor is triggered by a HIGH pulse of 10 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  digitalWrite(trigPin, LOW);
  delayMicroseconds(5);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
 
  // Read the signal from the sensor: a HIGH pulse whose
  // duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);
 
  // Convert the time into a distance
  cm = (duration/2) / 29.1;     // Divide by 29.1 or multiply by 0.0343
  inches = (duration/2) / 74;   // Divide by 74 or multiply by 0.0135
  
  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  
  delay(250);
}

View raw code

How the Code Works

First, you create variables for the trigger and echo pin called trigPin and echoPin, respectively. The trigger pin is connected to digital Pin 11, and the echo pin is connected to Pin 12:

int trigPin = 11; 
int echoPin = 12;

You also create three variables of type long: duration and inches. The duration variable saves the time between the emission and reception of the signal. The cm variable will save the distance in centimeters, and the inches variable will save the distance in inches.

long duration, cm, inches;

In the setup(), initialize the serial port at a baud rate of 9600, and set the trigger pin as an OUTPUT and the echo pin as an INPUT.

//Serial Port begin
Serial.begin (9600);
//Define inputs and outputs
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);

In the loop(), trigger the sensor by sending a HIGH pulse of 10 microseconds. But, before that, give a short LOW pulse to ensure you’ll get a clean HIGH pulse:

digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

We use the pulseIn() function to get the sound wave travel time:

duration = pulseIn(echoPin, HIGH);

The pulseIn() function reads a HIGH or a LOW pulse on a pin. It accepts as arguments the pin and the state of the pulse (either HIGH or LOW). It returns the length of the pulse in microseconds. The pulse length corresponds to the time it took to travel to the object plus the time traveled on the way back.

Then, we calculate the distance to an object, taking into account the sound speed.

distance = (traveltime/2) x speed of sound

The speed of sound is: 343m/s = 0.0343 cm/uS = 1/29.1 cm/uS

Or in inches: 13503.9in/s = 0.0135in/uS = 1/74in/uS

We need to divide the travel time by 2 because we have to consider that the wave was sent, hit the object, and then returned to the sensor.

cm = (duration/2) / 29.1;
inches = (duration/2) / 74;

Finally, we print the results in the Serial Monitor:

Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();

Source code with NewPing Library

You can also use the NewPing library. Download the library here.

After installing the NewPing library, you can upload the code provided below.

/*
 * Posted on https://randomnerdtutorials.com
 * created by http://playground.arduino.cc/Code/NewPing
*/

#include <NewPing.h>
 
#define TRIGGER_PIN 11
#define ECHO_PIN 12
#define MAX_DISTANCE 200

// NewPing setup of pins and maximum distance
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); 
 
void setup() {
   Serial.begin(9600);
}
 
void loop() {
   delay(50);
   unsigned int distance = sonar.ping_cm();
   Serial.print(distance);
   Serial.println("cm");
}

View raw code

How the Code Works

Getting the distance to an object using the NewPing library is much simpler.

You start by including the NewPing library:

#include <NewPing.h>

Then, define the trigger and echo pin. The trigger pin is connected to the Arduino digital Pin 11 and the echo to Pin 12. You also need to define the MAX_DISTANCE variable to be able to use the library.

#define TRIGGER_PIN 11
#define ECHO_PIN 12
#define MAX_DISTANCE 200

Then, you create a NewPing instance called sonar:

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

In the setup(), you initialize the Serial communication at a baud rate of 9600.

Serial.begin(9600);

Finally, in the loop(), you just need to use the ping_cm() method on the sonar object to get the distance in centimeters.

unsigned int distance = sonar.ping_cm();

If you want to get the distance in inches, you can use sonar.ping_in() instead.

Demonstration

Arduino UNO Board HC-SR04 Ultrasonic Sensor Module Arduino Demonstration

Upload the code to your Arduino board. Then, open the Serial Monitor at a baud rate of 115200.

The distance to the nearest object is printed in the Serial Monitor window.

Arduino with Ultrasonic Sensor Demo Serial Monitor

Wrapping Up

In this post, we’ve shown you how the HC-SR04 ultrasonic sensor works and how you can use it with the Arduino board. For a project example, you can build a Parking Sensor with LEDs and a buzzer.

If you are a beginner to the Arduino, we recommend following our Arduino Mini-Course that will help you get started quickly with this amazing board.

If you like Arduino, you may also like:

You can find all our Arduino projects and tutorials here.

We hope you found this tutorial useful. Thanks for reading.



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

150 thoughts on “Complete Guide for Ultrasonic Sensor HC-SR04 with Arduino”

    • Hello all, just got my first arduino, and i have this working. but for my project i need a second ultrasonic sensor. and i have no idea how to do that.
      ive added a triggerpin and an echo pin in the code for the second sensor, but how do i define to the code there are 2 sensors? do i need to copy the whole code again for the second sensor? or can the code run for both at the same time?

      Reply
      • Where you see number that I add number ‘2’, this is for the second sensor.

        int trigPin = 11; // Trigger
        int echoPin = 12; // Echo
        int trigPin2 = 9; // Trigger for second sensor
        int echoPin2 = 10; // Echo for second sensor
        long duration, cm, inches;
        long duration2, cm2, inches2;

        void setup() {
        //Serial Port begin
        Serial.begin (9600);
        //Define inputs and outputs
        pinMode(trigPin, OUTPUT);
        pinMode(echoPin, INPUT);
        pinMode(trigPin2, OUTPUT);
        pinMode(echoPin2, INPUT);
        }

        void loop() {
        // The sensor is triggered by a HIGH pulse of 10 or more microseconds.
        // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
        digitalWrite(trigPin, LOW);
        digitalWrite(trigPin2, LOW);
        delayMicroseconds(5);
        digitalWrite(trigPin, HIGH);
        digitalWrite(trigPin2, HIGH);
        delayMicroseconds(10);
        digitalWrite(trigPin, LOW);
        digitalWrite(trigPin2, LOW);
        // Read the signal from the sensor: a HIGH pulse whose
        // duration is the time (in microseconds) from the sending
        // of the ping to the reception of its echo off of an object.
        pinMode(echoPin, INPUT);
        pinMode(echoPin2, INPUT);
        duration = pulseIn(echoPin, HIGH);
        duration = pulseIn(echoPin2, HIGH);
        // Convert the time into a distance
        cm = (duration/2) / 29.1; // Divide by 29.1 or multiply by 0.0343
        cm2 = (duration/2) / 29.1;
        inches = (duration/2) / 74; // Divide by 74 or multiply by 0.0135 // Divide by 29.1 or multiply by 0.0343
        inches2 = (duration/2) / 74;
        Serial.print(inches);
        Serial.print(“in, “);
        Serial.print(cm);
        Serial.print(“cm”);
        Serial.println();
        Serial.print(inches2);
        Serial.print(“in2, “);
        Serial.print(cm2);
        Serial.print(“cm2”);
        Serial.println();

        delay(250);
        }

        Reply
  1. Hi, this is to me really helpful. Now I able to understand better how HC-SC04 work.. Hopefully you will keep on sharing this valuable knowledge.
    Thank you very much ^_^

    Reply
  2. make simple if use NewPing library.

    the code like this .

    #include

    #define TRIGGER_PIN 12
    #define ECHO_PIN 11
    #define MAX_DISTANCE 200

    NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

    void setup() {
    Serial.begin(9600);
    }

    void loop() {
    delay(50);
    unsigned int uS = sonar.ping_cm();
    Serial.print(uS);
    Serial.println(“cm”);
    }

    resource : http://playground.arduino.cc/Code/NewPing

    Reply
  3. Unfortunately you missed out the one thing that gives people trouble.
    If the HC-SR04 does not receive an echo then the output never goes low.
    Devantec and Parallax sensors time out after 36ms and I think 28ms respectively. If you use Pulsin as above then with no return echo the program will hang for 1 second which is the default timeout for Pulsin. You need to use the timeout parameter.
    http://arduino.cc/en/Reference/PulseIn
    The HC-SR04 barely works to 10 feet giving a total path length of 20 feet and a path time of about 20ms so set the timeout to something above that, say 25 or 30ms.
    If you put a resistor, say 2k2 between E and T then only connect to T you can use the HC-SR04 from just one Arduino pin. Look up single pin operation of ultrasonic sensors.
    Also if you are using a HC-SR04 with a PicAxe you need to up the clockspeed to at least 8MHz otherwise they don’t see the start of the echo pulse so pulsin never starts. The HC-SR04 works fine with a BS2.

    Reply
    • Hi David,
      I totally forgot that and some problems I wasn’t aware of.
      Next weekend I’ll try to update this post and add all those notes.

      Thanks for such a detailed comment and for improving my content!

      thanks again,
      Rui santos

      Reply
    • Hi David,
      I’ve added your comment to my blog post.
      You really explained well some stuff that I wasn’t aware of.

      I hope you don’t mind.
      Thanks for your expertise.

      Have a nice day,
      Rui

      Reply
  4. Fala amigo, beleza?
    Testando seu codigo esbarrei em um problema, quanto mais proximo um objeto do sensor, mais rapido o programa faz seu loop, achei isso muito estranho pois na ultima linha o “delayMicroseconds(300)” define basicamente que o loop sera dado a cada 300milisegundos (logico um pouco mais pq tem outros pequenos delays e tem o tempo de processamento), mas nao sei pq o loop fica mt acelerado, acho que ate a baixo de 300milisegundos.
    Como o meu programa depende desse tempo, basicamente é um buzzer que almenta a frequencia de apitos com a proximidade de um objeto, nao funcionou com seu codigo. Porem usando a biblioteca NewPing, e usando como base o codigo exemplo que o Imam postou esse erro foi resolvido. Sabe me explicar o porque?

    Reply
    • Olá Rodrigo,
      realmente é um erro um pouco estranho. Eu vou testar isso agora mesmo e tentar resolver.

      assim que consiga resolver altero este post.
      Pode sempre usar a biblioteca NewPing. É mesmo muito boa e simplifica imenso o nosso trabalho.

      Obrigado por notar esse erro.

      Abraço,
      Rui

      Reply
    • Olá Rodrigo,
      já resolvi o problema esqueci-me de fazer low ao trigPin no inicio do loop:

      digitalWrite(trigPin, LOW);
      delayMicroseconds(5);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);

      E isso estava a fazer com que o sensor se comporta-se de uma forma estranha. Já está resolvido.
      Obrigado!

      Abraço,
      Rui

      Reply
    • yes the Arduino can easily accomodate 4 ultrasonic sensors.
      Each sensor only requires 2 digitals pins. (4 ultrasonic sensors * 2 digital pins = 8)
      so you still have some pins left.

      But you need to right a good code so they don’t conflict with each other!

      Reply
  5. I glad of your work, but i want to know the internal working of the module. It consist of 3 ICs . I want to know the Working of them. Can you help me?

    Reply
  6. Hi . and thanks for this article .
    i have a question about the sensor . after one trigger does it continue to measure the distance , i mean if we want it to measure the distance for some time , do we need to send the trigger signal continuously?

    Reply
    • Hi Ali,
      I’m not sure if this answer is exactly what you’re asking…
      when you send the trigger after a few seconds you need to read that signal with the echo to see how much time it took the ultrasonic wave to touch the nearest object.
      So that means you need to keep repeating that process over and over again to measure the distance…

      Reply
  7. I have six of these…
    before connecting to the micro controller, all of them put 5v on trig at power on. is this the correct behavior?
    I understand that the micro controller is to put 5v on trig for 10us to trigger the pulse… can you explain how it can be correct to put 5v on trig as instructed, when 5v is already on trig on power up (without connecting to anything)?

    nice job with this write up… thanks

    Reply
    • The microcontroller puts 5V on the trigPin when you turn the digital pin of your Arduino to HIGH.

      When you do this digitalWrite(trigPin, HIGH);
      The trigPin of your ultrasonic sensor receives 5V.

      Reply
    • Input pins when not connected to anything are said to float and because the input impedance of them is high they can be affected by stray electrostatic voltages on anything, including your fingers. Hence voltage on them can be at an illegal value between the thresholds for logic 0 and logic 1 which can cause the internal circuitry to fail or lock up or generally do bad things. To avoid this a lot of input pins have either pull-up or pull-down resistors connected to them so that when the pin is not connected it will be in a known state.
      The Trig pin has a 10K pull up resistor connected between it and Vcc, on mine you can see the tiny surface mount 103 resistor on the back of the board by the header pins. So when the board is powered and no circuitry is connected to Trig the voltage on it will be at Vcc.
      The control computer must first set the pin to logic zero and then, when it wants to trigger the HC-04, set the pin to high for 10us before setting it low again.

      Reply
    • ha a same question i hope u may help me out
      i have even not connected the trig pin to the arduino and only the echo is connected but even though i am getting the echo valuse can u please justify this to me
      thanks in advance

      Reply
    • You can see what’s happening with the sensor with an Oscilloscope.
      But if you followed my tutorial and it’s not working for you, your ultrasonic sensor might be damaged.

      Reply
    • The sensors are cheap enough so the easy way to see if a sensor is working is to try another one. I have used maybe 20 of them without any problems until the other day when one stopped working. I swapped it and the replacement worked. Nothing was obviously wrong with the bad sensor but if I held it, it started working again so I resoldered the joints on the two transducer cans and the connector and now it works again.

      Reply
  8. Hey this is really useful stuff!

    I was wondering if you have ever used the Ultrasonic sensor to control a music shield? Im currently attempting this project and want the song to change depending on how far away you are from the sensor, just using 2 songs though.
    Any help will be muchly appreciated!

    Lorna

    Reply
  9. thanx a lot for this info. But I need your help,I am expecting reading from sensors in millimeters. Is it possible to have??
    Please give me a solution

    Reply
  10. I’ve tried a number of different sketches with my HC-SR04 and always have the same problem. Once the maximum range of the sensor is reached, a distance of zero is returned and then the sensor will not start working again. Once it has stopped I can move objects in front of it (like my hand) but continue to get no distance readings. It works fine until then, though. I realize no one has commented here recently, but if anyone has any idea what my problem is, please let me know. Maybe a defective sensor?

    Reply
    • Sam
      I have never had that problem. Can you post the sketches you have tried then I can test it with my HC-SR04s. I have them from several different manufacturers. Maybe yours is faulty.
      David

      Reply
      • I have also had this problem with cheap HCSR04 modules I got from aliexpress ($1 each oh well!). Once an “out of range” reading occurs, the device never works again, the output from echo just stays high all the time until you power it down and back up.

        I am looking for a solution too and have tried quite a few things including hardware and software with no luck so I feel like the reason they were a buck each was that they are simply defective “seconds” with some hardware flaw.

        But if anyone has any insights on this I would appreciate hearing about it.

        Reply
      • 4 out of 5 modules have the same problem. They work for a while. Then when I lay my breadboard on a flat surface, the modules stop reading. I can audibly hear a “tick tick tick” coming from the cans while it works. When it stops working the sound stops. I’ve found that if I blow on the can, the module resumea working again. Or I can flick it with my finger and it will resume. Odd.. has anyone else seen this issue?

        Reply
        • I am ordered over 100 of these sensors for a class, and well over 75% have this issue, regardless of which code, library, or timing I am using. A previous set of 100+ ordered last year do not have this issue, and the ticking cannot be heard.
          Flicking it or resetting the power seems to fix the problem until I max out the range or change distance quickly again.
          Did you find a solution or cause to the issue?

          Reply
    • Sam,

      I have encountered the same issue. I ordered three sensors, one of which performs as it should, one is completely DOA, and the third behaves as you describe. I have found that it will start working again if I clap my hands or snap my fingers near the sensor. It will then work for a while but will eventually hang again. I have been searching the web for a programatic way of correcting it, but haven’t found an easy way. The closest I have found is the last post at:

      http://forum.arduino.cc/index.php?topic=55119.0

      Reply
  11. I have the same problem that Sam Khoury has. Once in a while the sensor goes into a mode where the echo pulse is very sharp indicating almost zero distance and the only way to recover from this is to disconnect the sensor and reconnect it. I also found that when the repetition of trigger is faster than 700ms this type of problem crops up. Presently I use a repetition interval of 3 to 4seconds.

    Reply
  12. Olá Rui.
    Digamos que eu queira colocar o trigger e o pin nas saidas analógicas do Arduino.
    Eu teria que colocar TRIGGER_PIN A4 e ECHO_PIN A5?

    Reply
    • They are the conversion factors for the speed of sound, to converet the time – for the sound to go out, hit the target and return – to distance

      Reply
  13. Some knock-off models of the HC-SR04 do not implement a timeout if no echo is detected at all. In that case, the echo pin will simply remain high forever and will not generate any new pings, regardless of what you do with the trigger pin. The original model from Robot Electronics times out after 36 ms and does not have this problem, but many (all?) cheap knock-off models do.

    You can reproduce the problem easily by covering the receiver transducer with your thumb, then removing your thumb. If your sensor doesn’t have a timeout, it will stop generating pings and the only way to recover is to power cycle the sensor.

    A workaround that works for me so far is to test the state of the echo pin 100 ms after triggering a ping. If it’s still high, you’re in a stuck state. If you wire power to the sensor through a transistor and control that transistor via another pin, then you can power cycle the sensor via software and get back to a working state.

    Reply
    • I think I was the first person to point out that the HC-SR04 doesn’t time out if it doesn’t receive an echo unlike the SRF04 from Robot Electronics.
      I have used a lot of the HC-SR04 modules from different manufacturers in China and non of them have needed power-cycling if they don’t receive an echo. Always a new trigger pulse results in a new ping being sent.
      It is possible if you try to use them on a single uController pin by wiring Echo and Trigger together that they will lock up, however you should never wire them like that since the the uController pin when set to output to trigger the module will fight with the Echo pin (an output) and could damage both the HC-SRF04 and the uController.
      If you connect the Echo and Trigger pins through a 2k2 resistor and connect the uController pin to the Trigger pin (not the Echo pin) then the 2k2 resistor stops the pins fighting and you can use a single uController pin without any problems.

      Reply
      • I can confirm without a doubt that some of the very cheap (I’m talking about 80 cents including shipping!) units do lock up even if you use both trigger and echo on different controller pins. I can also confirm that putting a 2k2 resistor between trigger and echo to run in 1 pin mode doesn’t help (wouldn’t expect it to since 2 controller pin mode doesn’t).

        They are not even consistent. i bought 10 of the 80 cent modules and 5 of them are very, very unstable and lock up very easily. Others only lock up occasionally. Another oddity (that others have also pointed out) is that sometimes if they lock up if you touch them with your finger they unlock, or even if you snap your fingers close to them. Apparently this finally triggers the sensor to sense a ping.

        I upgraded to $2 devices from itead studio and they work great. They do have a 36 millisecond timeout built in and I’ve used 5 different units from them with no problems.

        Reply
        • Well I have used maybe 30 from 6 different batches with different PCBs and have yet to have one that locks up.
          My understanding is that the HC-SR04 was designed for a bicycle alarm where it is a good thing if nobody is near and hence no echo , so it makes no sense for them to lock up.
          There is always the possibility that if the Trigger pin floats because the uController pin connected to it has been made an input then the module will be susceptible to static – ie the approach of fingers. Correcting the software or using a 10k pull down would stop that.
          If I come across one that doesn’t work I’ll post a comment.

          Reply
  14. Hi,
    Thank you for the article. It is great!
    Can anyone please tell me, can i use this sensor 100 meters apart from arduino connected via wires.

    Reply
    • Murtaza – of course you can’t, it is just basic electronics, it is like asking “can I get a 100m USB lead?” or will my phone work underwater?”. 100m of wire has too much inductance, resistance and capacitance for a signal from the Arduino to reach the sensor or for a reply from the sensor to reach the Arduino. You could do it with two Arduinos and a radio link between them and the HC-SR04 connected by short wires to one of them, or the two Arduinos could be connected using RS485 communication shields and 100m of suitable cable.

      Reply
  15. Hi Rui,

    thank you for your helpful article.

    I just got the idea to take the last 10 distance results in a global queue variable to detect if my bot is moving at all (maybe it ran onto an “invisible” obstacle). I used the standard deviation of the distance array for that and although i have quite different results every time i measure i found 1cm enough to detect if i’m stuck in about 1 – 5 seconds.

    Maybe this will work out for others, too.

    Do you have a method for improving the quality of measurements?
    I found this one but seems complex to me:
    ijcte.org/papers/118-G227.pdf

    Would you agree to take the standard deviation for that?

    Do you have a much better approach for motion sensing?

    Kind regards, Bernd

    Reply
  16. Hi David,
    I can also confirm, waht was said about the cheap HC-SR04. It locks up very fast and can only be resetted by power off/on.
    Mine also shows the effect described before, like when you cover the sensor with your finger, its stops immediately. Bought 10 of these and tested 2 so far, both are behaving the same. Seems to be just crap from china. Should have bought the real ones.
    Have tested it with 5 different scripts, motor shield v1 and v2, but it all comes down to the sensor failing.
    Cheers, Matthias

    Reply
    • The ones from iTead Studio are about $2 each and they work reliably for me every time.

      If you buy the ones that are like $1 each, well, you get what you pay for. Some of them work and some don’t. I think it just depends on what batch you get.

      Reply
  17. Marza,
    Regarding: Can anyone please tell me, can i use this sensor 100 meters apart from arduino connected via wires.

    Maybe.
    Here are things to consider. The cable adds capacitance. For CAT5 cable the capacitance per foot might be 52pF/meter so you have 5200 pF loading on the I/O lines. It may be a problem, but I doubt it. Assuming the output impedance (driving resistance) of the I/O pins is as high as 1K Ohm , then the time constant of the I/O signals (the product of the R and the C) is about 1×10^3 x 5200*10^-12 = 5.2 x 10 ^-5. Or 0.052 mS.
    This will make an unmeasurebly small error.

    Now the long wires themselves add a litter resistance. It is less than 0.2 ohms / meter so for 100 meter it is <20 ohms. Again not important when the I/O pins "impedance" (which is like resistance) is already probably 1K ohm.

    The only problem with long wires is they become antennas for stray signals and pickup of induced surges from lightning. So it may work fine until one day lighting ruins it all.

    I hope this helps and if you try it let us know.

    Reply
  18. Hey! I found it totally useful and interesting! But i have got a question… This may sound totally stupid amd weird… Can I just connect an ultrasonic sensor to a buzzer and them use it for object detection? I mean… Is the arduino that important… Can’t there be a simple circuit?
    Hope i’ll get my answer…. Thanks

    Reply
      • What i actually want to make is a smart blind walking stick.. Someone told me that the arduino has to be connected to the pc for the ultrasonic sensor to work… But if i keep it connected, then i can’t move my stick?…. Yea, i know i am totally stupid and i know nothing about these sensors… But could you help me out here sir?

        Reply
  19. Hey…what i actually want to make is a smart blind walking stick with an ultrasonic sensor…. Someone told me that the arduino has to be connect to the pc for the ultrasonic sensor to work… So if i hav to keep the arduino connected, then i can’t move my stick?… I know i am stupid and j know nothing about these sensors… Could you please help me out here sir?

    Reply
    • You need to learn about electronics, microcontrollers (the Arduino is a microcontroller) and programming/software otherwise you won’t understand the answers. There are plenty of tutorials on the web for electronics and programming the Arduino.

      Reply
    • The arduino does the calculation for the distance. If you just use the echo pin, it will be outputting a high on every echo irrespective of the distance. That may not give you any distance based control but your alarm device may get continuously triggered irrespective of distance.

      Reply
      • You probably ought to buy an Arduino Uno and an Ultrasonic sensor and then work through the examples here. You will find that you only need the PC connected for programming the Arduino or for displaying the distance measurement, (if that is what you want to do).

        Reply
    • Once you program and test small arduino Nano model and then you dont need PC. You have to power arduino and HC-SR04 with 5v which you can do with small batteries. Arduino will need PC only when you are uploading and testing the program.

      Reply
  20. Hi, would anyone be able to tell me how the distance is actually calculated. Everywhere I look, the value of 58.2 shows up, and in this example that has been halved as the distance value hasn’t been. I know that the distance needs to be halved as we are measuring the distance for the wave to hit an object not hit an object and bounce back, but this number just appears with no explanation anywhere?

    Reply
      • Hair will most likely scatter and absorb the sound wave unless the receiver is quite close, you will have to experiment. Then again what do you mean by height of the person? Do you mean to the top of their head or the top of their hair, reading off the top of their hair would in lots of cases be meaningless. Think about what you are doing.

        Reply
  21. Thanks for the Tutorial! but I don’t understand why mine doesn’t work. The Serial monitor shows a constant value (that feels like random and not the actual distance). When I touch the USB connector, the value shows “0in, 0cm” (infact, touching some metal surface of the arduino or of the Ultrasonic sensor leads to this result). Is this some kind of grounding issue? Is there a way to fix this? Is any one of the component bricked? Thank you in advance.

    Reply
    • Hi.
      If the tutorial is not working, it may be because of some of the following reasons:
      – your ultrasonic sensor is faulty – you need to get a new one;
      – the wiring is not correct – double-check the wiring using the schematic diagram provided;
      – also make sure you have selected the right baud rate on the Serial Monitor.
      I hope this helps.
      Regards,
      Sara 🙂

      Reply
  22. My HCSR04 ultarsonic sensor is not working properly.. with no object in front of sensor. The circuit is working… which I don’t want.
    What to Doo..?

    Reply
    • Hi.
      What do you mean by “not working properly”. Can you provide more details?
      Are you getting any errors on your serial monitor?
      Regards,
      Sara

      Reply
    • Hi Sabine.
      We don’t have any tutorial for what you are looking for.
      But there are several libraries for MicroPython that you can use for ultrasonic sensor, for example:
      github.com/rsc1975/micropython-hcsr04
      I hope this helps.
      Regards,
      Sara

      Reply
  23. Hi,
    I am using ultrasonic sensor to classification of milk based on viscosity. So for that i want the code so please help me
    condition:
    If range is between 0cm to 4cm then display viscosity is high
    If range is between 4cm to 7cm then display viscosity is medium
    If range is between 7cm to 10cm then display viscosity is low.

    Please help me for finding the code

    Reply
  24. HI! Sara Santos
    can we place acrylic clear sheet of 2mm in front of the sensor and mount for making it waterproof and get the level of the water?

    Please suggest, we are planning to make some application; where the sensor has to be placed inside the water container and it should not be visible by anybody when the container cap is open and if by chance the container falls down or kept upside down by mistake the sensor should not get damaged by water spill over it.

    Please let us know, so we can make an enclosure and give a slot cut with acrylic clear glass of 2mm mounted in front of the sensor for getting the accurate water level.

    Thank You.
    Darshan

    Reply
    • Hi Darshan.
      This ultrasonic sensor was made to work when the signal is transmitted on air.
      I think that if you try to cover it with an acrylic glass, it will interfere with your results and you won’t have accurate measurements.
      However, take a look at this discussion in the Arduino forum and see if something can help with your project: forum.arduino.cc/index.php?topic=349192.0
      Regards,
      Sara

      Reply
  25. Hai sir, I have interfaced ultrasonic sensor with Arduino using serial monitor. Now, I want to interface LCD to monitor the distance values could you please provide the schematic to interface LCD with Arduino.
    I have purchased the ultrasonic sensor
    uitechies.co.in/BBBcircuits/product.php?product=ultrasonic-range-finder-module-sensor-distance-measuring-transducer

    Reply
  26. Are we supposed to use a screen?
    Where does the output gets displayed.. I’m new to this I did the wiring as you’ve shown and typed the code similarly but I don’t understand what’s supposed to happen next… It’s doing absolutely nothing… Am I missing out of something too obvious? Sorry I’m a newbie with Arduinos

    Reply
    • Hi.
      With the Arduino connected to your computer, open the Arduino IDE Serial Monitor (magnifying glass icon at the top right corner) and you should start seeing the distance of obstacles to the sensor.
      Regards,
      Sara

      Reply
  27. Hello Santos family,

    I have noticed the Arduino IDE is very often used in your projects.
    For experienced users is that no problem, however when you are not that familiar with programming it could be very frustrating to get things work properly.

    I found another way to resolve this in the ESP Easy (mega) flasher Tool.
    I use the Wemos D1 mini shields to stack compact solutions together.
    It is in combination with Domoticz (for reporting) a fine combination of Tools.

    What I noticed with the Ultra Sonic Range finder is that it will not work with Wemos D1 Mini (ESP8266 System on Chip (SOC)) but when connected to a NodeMCU Develop SOC it works instantly.

    Is it possible to tell if there is a significant difference between the SOC for the Wemos D1 mini and the NodeMCU Dev SOC?
    Or is this a classic situation of comparing Appels and Peers? (Dutch expression).

    Would be nice if it is possible for you comment on this.

    Best regards
    Arjen
    Netherlands

    Reply
  28. Lots of great comments and it may be covered already but so many to look up I thought I’d just ask.
    I want to measure the water level of a small cylinder tank.
    What would I need to change or add to the code to get it to read in milliliters.
    TIA

    Reply
  29. You would have to know the surface area of the tank so you could convert surface rise or fall to volume change. [millimetres=distance, millilitres=volume]

    Reply
      • 1 – Research how to calculate the area of a circle in centimetres
        2 – Research how to calculate the volume of a cylinder in cubic centimetres
        3 – Research the volume of a millilitre in cubic centimetres
        Then get back to me.

        Reply
  30. i have attached a buzzer & the problem is when water level reaches 100% sensor value goes 100% then 99% for few times this is due to water is pumping to the tank, so the buzzer also act accordingly. is there any way to correct this issue?

    Reply
  31. I know this is a very old thread but for correctness I note at the Top you show

    Pins
    VCC: +5VDC
    Trig : Trigger (INPUT)
    Echo: Echo (OUTPUT)
    GND: GND

    But in your sketch

    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);

    Could be confusing to some?
    Clearly your “PINS” description is inverted.

    Cheers
    Ralph

    Reply
    • Only confusing to those who don’t understand ‘input’ and ‘output’
      The HC-SR04 Trigger pin is marked INPUT because it is an INPUT pin which receives the trigger pulse, and the Echo pin is marked OUTPUT because it outputs the return pulse which gives the distance.
      The Sketch has pinMode(trigPin, OUTPUT);
      because that pin is connected to the HC-SR04 Trigger pin and on the Arduino it has to be set to OUTPUT so it can generate the trigger pulse to the HC-SR04.
      The Sketch has pinMode(echoPin, INPUT);
      because that pin is connected to the HC-SR04 Echo pin and on the Arduino it has to be set to INPUT so it can receive the trigger pulse from the HC-SR04.

      Try it out, change the sketch to what you think is right and you will find nothing works and then probably blame the Chinese HC-SR04 as being faulty.

      Reply
  32. is it possible to interchange the trig and echo pins. what i want to do is to transmit on one transducer and receive on the other, thereafter transmit on the second and receive on the first

    Reply
  33. hi, it is really helpful to understand the coupling of the sensor with the Arduino.
    thanks in advance.
    I need some info. i am intending to connect 5 ultrasonic sensors in my project. Then how should i connect the Trig and Echo pins. either i should mutually join all respective wires of all five sensors and then connect the wires to the arduino digital pins, or i should connect the trig and echo pins of all five sensors to connect in the arduino, separately.
    hope you will hear from me soon.

    Reply
    • Hi.
      You should connect them to separate pins. Otherwise, you won’t know to which sensors the measurements correspond.
      Regards,
      Sara

      Reply
  34. If you want to try project with visualisation of data at remote webserver where ESP will send datas, you can use mine project: arduino.clanweb.eu/studna_s_prekladom/?lang=en It is free to use at test web interface. You can also read datas from website by using JSON client that can parse datas. So you can integrate height of water level and its volume to your home automatication – Hassio / Domoticz / Loxone.

    Reply
  35. I have had many problems getting the Ultra Sonic sensor to work in combination with servo motors and/or encoder motors. From my experience and from what I have read they all use the same timer and with more than one device the timer(s) get confused which pulse they are timing. Random, jerky and erratic movements result ruining the entire project. Seems like a bad design to me. Is there a solution to this?

    Reply
    • The bad design is using Arduino libraries when you have no idea whether they use the same Arduino resources or not. I have used lots and lots of servos and lots of the HC-SR04 on Arduinos without any problems because I gave up using Arduino libraries from the beginning after discovering that the IR library causes the servo library pulses to be way off as well as being useless for receiving IR commands. Unless they have changed the design of the HC-SR04 recently you must use the pulsein timout – pulseIn(pin, value, timeout) in case the HC-SR04 does not see anything, otherwise the code waits for the default pulseIn() timeout which is 1 second according to the Arduino documentation. I use 20,000 for 20ms timeout which corresponds to about 10 foot which is more than the HC-SR04’s useful range.

      Reply
  36. situation : assuming blind person is in problem when buzzer beeps using ultrasonic sensor( range 50 cm ) then he presses a button which is connected to his stick . after pressing button , a msge must be sent ( using gsm module ) to certain phone number saying ” i am in danger ” . and with this msg , is live location ( using gps module )must be sent to that same number.. ( location in terms of latitude and longitude) i need answer in c/c++ sim900a

    Reply
  37. Hi! thanks in advance. i would like to know if it possible to control volume of a mp3 file just by distance. so when i get close to de HC-SR04 the volume turns up, and when i get far the volume goes down.

    thanks!

    Reply
  38. Hi Rui
    Thanks for this tutorial, I have tested my sensors with Newping library also having found about it from your tutorial.

    I want to know distance as well as angle of the object.
    I saw Arduino Radar based on HC-SR04 also. It requires a small servo motor to sweep the sensor to find out distance and angle.
    I wanted to get that functionality without servo so I guessed I will have to use multiple HC-SR04 placed at different angles to cover the area under observation. I guess 5 sensors will be sufficient. Naturally, when object is there, mostly two sensors will be able to ‘see’ it and report the distance. The sensor which reports closest distance is the one I intend to use for measurement of distance and angle.
    When two sensors pickup the object presence, I guess I should use mean(average) of the angle of both sensors. I hope I am clear enough of the requirement. Once this logic is tested, I can use distance data also to fine tune the angle. For example, If sensor A is reporting the distance of 24 inches and sensor B is reporting distance of 30 inches, the angle of the object is not exactly where sensor A is facing but moved slightly towards sensor B. When the object moves closer to sensor B, both distances will get almost equal measurement and then the angle is exactly between angle of both sensors.
    Logically these calculations seem ok to me. Please give suggestions and guidance if I am on the right track.
    I hope to see your tutorial on Doppler radar sensor RCWL-0516. It has very broad vision of 270 degrees so I chose ultrasonic sensors as I wanted angle of object calculations.
    Have a great time ahead !

    Reply
    • The TRIG_PIN is used to send the trigger signal, and the ECHO_PIN is used to receive the echo signal.
      The pulseIn() function measures the duration of the pulse from the echo pin, which corresponds to the time taken for the ultrasonic wave to travel to the object and back.
      The speed of sound is approximately 343 meters per second (or 34300 cm/s). The formula used in the code calculates the distance based on this speed and the time of flight of the ultrasonic wave.
      The calculated distance is then printed to the Serial Monitor.

      Reply

Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.