Ultrasonic Sensor HC-SR04 and Arduino Tutorial

In this Arduino Tutorial we will learn how the HC-SR04 Ultrasonic Sensor works and how to use it with the Arduino Board. You can watch the following video or read the written tutorial below.

 

How It Works – Ultrasonic Sensor


It emits an ultrasound at 40 000 Hz which travels through the air and if there is an object or obstacle on its path It will bounce back to the module. Considering the travel time and the speed of the sound you can calculate the distance.

Ultrasonic-Sensor How it Works

The HC-SR04 Ultrasonic Module has 4 pins, Ground, VCC, Trig and Echo. The Ground and the VCC pins of the module needs to be connected to the Ground and the 5 volts pins on the Arduino Board respectively and the trig and echo pins to any Digital I/O pin on the Arduino Board.

In order to generate the ultrasound you need to set the Trig on a High State for 10 µs. That will send out an 8 cycle sonic burst which will travel at the speed sound and it will be received in the Echo pin. The Echo pin will output the time in microseconds the sound wave traveled.

Ultrasonic Sensor Diagram

For example, if the object is 10 cm away from the sensor, and the speed of the sound is 340 m/s or 0.034 cm/µs the sound wave will need to travel about 294 u seconds. But what you will get from the Echo pin will be double that number because the sound wave needs to travel forward and bounce backward.  So in order to get the distance in cm we need to multiply the received travel time value from the echo pin by 0.034 and divide it by 2.

Ultrasonic-Sensor-Equasions


Components needed for this tutorial


You can get these components from any of the sites below:

*Please note: These are affiliate links. I may make a commission if you buy the components through these links.
I would appreciate your support in this way!

Source Codes


First you have to define the Trig and Echo pins. In this case they are the pins number 9 and 10 on the Arduino Board and they are named trigPin and echoPin. Then you need a Long variable, named “duration” for the travel time that you will get from the sensor and an integer variable for the distance.

In the setup you have to define the trigPin as an output and the echoPin as an Input and also start the serial communication for showing the results on the serial monitor.

In the loop first you have to make sure that the trigPin is clear so you have to set that pin on a LOW State for just 2 µs. Now for generating the Ultra sound wave we have to set the trigPin on HIGH State for 10 µs. Using the pulseIn() function you have to read the travel time and put that value into the variable “duration”. This function has 2 parameters, the first one is the name of the echo pin and for the second one you can write either HIGH or LOW. In this case, HIGH means that the pulsIn() function will wait for the pin to go HIGH caused by the bounced sound wave and it will start timing, then it will wait for the pin to go LOW when the sound wave will end which will stop the timing. At the end the function will return the length of the pulse in microseconds. For getting the distance we will multiply the duration by 0.034 and divide it by 2 as we explained this equation previously.  At the end we will print the value of the distance on the Serial Monitor.

/*
* Ultrasonic Sensor HC-SR04 and Arduino Tutorial
*
* Crated by Dejan Nedelkovski,
* www.HowToMechatronics.com
*
*/

// defines pins numbers
const int trigPin = 9;
const int echoPin = 10;

// defines variables
long duration;
int distance;

void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
}

void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);

// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);

// Calculating the distance
distance= duration*0.034/2;

// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
}

If you want to display the results from the HC-SR04 Ultrasonic Sensor on an LCD you can use the following source code:

/*
* Ultrasonic Sensor HC-SR04 and Arduino Tutorial
*
* Crated by Dejan Nedelkovski,
* www.HowToMechatronics.com
*
*/

#include <LiquidCrystal.h> // includes the LiquidCrystal Library

LiquidCrystal lcd(1, 2, 4, 5, 6, 7); // Creates an LCD object. Parameters: (rs, enable, d4, d5, d6, d7)

const int trigPin = 9;
const int echoPin = 10;

long duration;
int distanceCm, distanceInch;

void setup() {
lcd.begin(16,2); // Initializes the interface to the LCD screen, and specifies the dimensions (width and height) of the display

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

void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);

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

duration = pulseIn(echoPin, HIGH);
distanceCm= duration*0.034/2;
distanceInch = duration*0.0133/2;

lcd.setCursor(0,0); // Sets the location at which subsequent text written to the LCD will be displayed
lcd.print("Distance: "); // Prints string "Distance" on the LCD
lcd.print(distanceCm); // Prints the distance value from the sensor
lcd.print(" cm");
delay(10);
lcd.setCursor(0,1);
lcd.print("Distance: ");
lcd.print(distanceInch);
lcd.print(" inch");
delay(10);
}

86 Responses

    • Dejan Nedelkovski

      The problem might be that you are using Arduino DUE, which has 3.3V pins and the ultrasonic sensors is working with 5V. Try using an resistor at the echo pin, as the 3.3V are fine for the Trig pin, but the Echo pin of the sensor will output 5V to your Arduino DUI which might damage it.

      Reply
    • Rhydo

      Make sure your trig and Echo pins are connected to digital pins 9 and 10 instead of 11 and 12.

      Reply
  1. IAN

    Unfortunately I get the same 0, 0, ….. response for the ultrasonic sensor on the monitor as well using Mega 2560 using just the sensor code by itself???
    Any other suggestions?
    Cheers, Ian

    Reply
  2. Haravey

    Great video. Thanks. I’m trying to set this up to trigger a gate or relay at a predefined range to set off a light if something gets too close. Have you already developed a sketch for this scenario. I just can’t seem to get it to work correctly myself. Thanks.

    Reply
    • Dejan Nedelkovski

      Thanks! Well this is a tutorial that can help you understand the basic working principle of the sensor and the code to get it working with the Arduino, but I don’t have a specific code as what you have described. Every project is a unique and needs a unique code, but I don’t make custom codes. I hope watching some of my other tutorials as well, will get your code writing knowledge good enough so you can make your own code for your project. Cheers!

      Reply
  3. Thor

    Hey, I got everything working and your tutorials are great! My display works, but it is just a blue screen. It is just blue and no numbers or anything on it, please help!

    Reply
    • Dejan Nedelkovski

      Well the problem is the contrast of the display. Use a potentiometer to adjust the contrast (as shown in my Arduino LCD Tutorial) or make a voltage divider with two resistors.

      Reply
  4. Harvey

    Can u email me or update the diagram of this project by adding the connections for the 16×2 lcd green screen ty in advance this website was a real help to me as my first arduino project and I use arduino uno is that OK or I have to change something in ue given project waiting for a quick response:)

    Reply
  5. Sougata

    Hey Can you please upload/ Mail me the code and the diagram for measuring X-Axis And Y-Axis distance at the same time… Thanks

    Reply
    • terry schulz

      hi i have been working on HC-SR04 Ultrasonic Module and was wondering if you could send me a schematic of the project with the lcd hook up thank you for your time

      Reply
    • Aiden

      Hi Sougata, Brilliant that you managed it! Could you give me the code? Thanks.

      Reply
  6. Judy Kathryn

    Is the source code for the sensor and LCD is under one sketch?? Or i need to use two arduino boards?? And if so, how can i connect the two then? 🙂

    Reply
  7. Gaurav Jagannath Alande

    can you send me the code of interfacing arduino with HCSR-04 sensor -SG-90 servo motor n lcd with buzzer interfaing send me code plz

    Reply
  8. Ton

    Dear Dejan, I am building a simple robot with this sensor. The problem is this: I want to avoid a collision at a distance of about 50 cm. How do I implement in code this value in the simple software I made. (the robot is programmed to drive an eight) with simple code as digitalWrite HIGH or LOW on two pins.

    Regards, Ton.

    Reply
    • Dejan Nedelkovski

      Well the sensor can detect objects at that distance so I guess using some “if” statements you could make a simple code for avoiding collisions.

      Reply
  9. Pramod

    Hi Dejan

    Can I use HCSR 04 to send data to another HC SR04? I mean making one to act as transmitter and other as receiver? If yes how can I modify the code?

    Reply
  10. rakan

    Dear,
    I have an idea to measure the amount of water in a water tank.
    It has been seen on your video experiment to Motion Sensor.
    Question: Is it possible to transfer centimeter change in the screen to a percentage, for example 40%, 50%.
    Thank.
    Rakan

    Reply
  11. William

    Dear, it possible the ultrasonic can detect the water leakage on the water pipe? mean the ultrasonic can receive the frequency or other value to show that when the water pipe has leakage, the value will changing? thanks

    Reply
    • Dejan Nedelkovski

      Well I’m not quite sure about this. I guess the ultrasonic wave could bounce when it would hit the water but I can’t say whether it would work for your idea.

      Reply
      • William

        Sir, because i need use ultrasonic sensor to detect the water pipe leakage which is receive the frequency / pulse from the water pipe, it possible the ultrasonic sensor can receive the frequency/ pulse ?? since this is ultrasonic project, would u can take time explain the concept of the ultrasonic sound use in detect water pipe leakage, i very confuse, thanks for reply me….

  12. asda

    MY HC SR04 is always gives maximum output 24 cm .
    what to do now >

    Reply
  13. yoangel

    hello, if I want the measurement is not displayed in cm, if not in liters or ml as should be the formula? since I want to use this sensor to measure the water level of a tank

    Reply
  14. Anant

    Hey Dejan, is it possible to add a sound in the output so that the distance can also be used by the blinds!!

    Reply
  15. fatso

    i connected the sensor to pic 16f877a and i wanted to measure the volume of water in a tank but i m getting false results what might be the problem

    Reply
  16. Malik

    hi, i have checked this and many other codes but it is not giving accurate distance , only giving 2 inches. In addition I want to modify the range how I can do that?

    Reply
  17. Nicky Puff

    Dude, your tutorials are fcking awesome !!!
    I never find like this tutorial…
    easy to understand, easty to implement… so yeah 😀

    Do you have private contact ? i have final project in my colege and need new idea from you… Could you ? 😀

    Thanks so much

    Reply
  18. Mike Crawford

    Hi mate, I wonder how to graph the data cast from the Ultrasonic Sensor on app inventor, could you help me with it? Thx and best regards.

    Reply
    • Dejan Nedelkovski

      Hi there. Well sorry but all I can say is to check my tutorial on app inventor and in combination with this tutorial, make the project on your own.
      My work is teaching the basics of a particular sensor, module or a program, and your are that one that should use the knowledge gained from those tutorials to make a specific project.
      Cheers!

      Reply
  19. Agus salim

    hi…nice project1
    i have a question,,
    what code arduino mega match with another tipe of arduino?like a nano,uno..etc
    thank you

    Reply
  20. brahim

    I want to determine the coordinates(x,yz) of a point in space(room for exemple) by using ardouino, is that possible? and how to do it ?

    Reply
    • Dejan Nedelkovski

      You might be able to achieve that using this ultrasonic sensor. If you know the angle and the distance to the object you can determine it’s coordinates.

      Reply
  21. Gustavo

    is there any way to reduce te maximun distance measured?? great tuto by the way

    Reply
  22. brian burroughs

    hi do you have a wiring schematic for the whole thing combined? the distance sensor and the lcd?

    Reply
  23. brian burroughs

    have you got a wiring diagram for the distance sensor combined with the lcd?

    Reply
  24. brian burroughs

    Quick question Dejan, I want to hook the distance sensor up with a raspberry pi 3, all tutorials I see seem to use resistors, how come ya don’t need them with the arduino but ya need them with the pi?

    could i do it on the pi without resistors?

    Reply
  25. carmine

    hello i am carmine from rome,
    it is possible to change the absolute reading to a relative reading with a potentiometer change to a relative distance on the display?
    Thank you

    Reply
  26. Chris

    Can the ultrasonic sensor turn on 24/7? for everyday? Will it burn or get hot? Thanks

    Reply
  27. naja

    hello its is true this sensor can detect from 2cm – 4meter? and if distance over than 4meter, what will show at lcd display?

    Reply

Leave a Reply

Your email address will not be published.