Complete Guide for Ultrasonic Sensor HC-SR04 with Arduino

This article is a guide about the popular 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 in your projects. We provide a schematic diagram on how to wire the ultrasonic sensor, and an example sketch to use with the Arduino.

Description

The HC-SR04 ultrasonic sensor uses sonar to determine distance to an object like bats do. It offers excellent non-contact range detection with high accuracy and stable readings in an easy-to-use package. It comes complete with ultrasonic transmitter and receiver modules.

Features

Here’s a list of some of the HC-SR04 ultrasonic sensor features and specs:

  • 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
  • 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 transmitter (trig pin) sends a signal: a high-frequency sound.
  2. When the signal finds an object, it is reflected and…
  3. … the transmitter (echo pin) receives it.

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.

HC-SR04 Ultrasonic Sensor Pinout

ultraPins

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

Where to buy?

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

51tbSvuOcAL

Arduino with HC – SR04 Sensor

This sensor is very popular among the Arduino tinkerers. So, here we provide an example on 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.

Note: There’s an Arduino library called NewPing that can make your life easier when using this sensor.

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!

Schematics

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-SR04 Arduino
VCC 5V
Trig Pin 11
Echo Pin 12
GND GND

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 pins is connected to digital Pin 12:

int trigPin = 11; 
int echoPin = 12;

You also create three variables of type long: durationcmand inch. 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 inch 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);

Then, you can read the signal from the sensor – a HIGH pulse whose duration is the time in microseconds from the sending of the signal to the reception of its echo to an object.

duration = pulseIn(echoPin, HIGH);

Finally, you just need to convert the duration to a distance. We can calculate the distance by using the following formula:

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 traveltime by 2 because we have to take into account that the wave was sent, hit the object, and then returned back 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

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

After installing the NewPin 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(), to get the distance you just need to use the ping_cm() method on the sonar object. This will give you 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.

Troubleshooting

NOTE: “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.” by David Buckley

Thanks to my friend David to leave such an helpful comment!

Wrapping Up

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

If you are a beginner to the Arduino, we recommend following our Arduino Mini Course that will help you getting 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 program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »

Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »


Enjoyed this project? Stay updated by subscribing our weekly newsletter!

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

  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 ^_^

  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

  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.

    • 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

    • 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

  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?

    • 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

    • 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

    • 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!

  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?

  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?

    • 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…

  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

    • 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.

    • 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.

    • 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

    • 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.

    • 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.

  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

  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

  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?

    • 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

      • 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.

      • 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?

        • 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?

    • 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

  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.

  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?

    • 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

  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.

    • 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.

      • 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.

        • 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.

  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.

    • 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.

  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

  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

    • 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.

  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.

  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

      • 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?

  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?

    • 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.

  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?

  21. Hello sir i have a question how can i measure the human height if the wave never reflected because of our hair?

      • 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.

  22. 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.

    • 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 🙂

  23. 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..?

    • 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

    • 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

  24. 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

  25. 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

    • 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

  26. 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

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.