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 the HC-SR04 Ultrasonic Sensor Works

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.

Components needed for this tutorial

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

Disclosure: These are affiliate links. As an Amazon Associate I earn from qualifying purchases.

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 ultrasonic burst which will travel at the speed of 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

Arduino and HC-SR04 Ultrasonic Sensor Code

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.

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

// defines variables
long duration;
int 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.

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
}

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.

// 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);

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.

// 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);

At the end we will print the value of the distance on the Serial Monitor.

Here’s the complete code:

/*
* Ultrasonic Sensor HC-SR04 and Arduino Tutorial
*
* 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);
}

See also: Arduino Range Measurer and Digital Spirit Level Project

Arduino Ultrasonic Sensor and LCD Display Example

Here’s another example how to use the ultrasonic sensor with Arduino and display the results on an LCD.

Arduino Ultrasonic Sensor and LCD Display Example

You can connect the ultrasonic sensor and the LDC as following:

Arduino ultrasonic sensor and the LDC circuit diagram

The code measuring the distance is pretty much the same as the basic example. Here, instead of printing the results on the serial monitor we print them on the LCD. If you need more details how to use and connect an LCD with Arduino you can check my particular tutorial for it.

/*
* Ultrasonic Sensor HC-SR04 and Arduino Tutorial
*
* 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);
}

I hope you enjoyed this tutorial and learned something new. Feel free to ask any question in the comments section below and don’t forget to check out my collection of Arduino Projects.

95 thoughts on “Ultrasonic Sensor HC-SR04 and Arduino Tutorial”

    • 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
  1. 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. 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
    • 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. 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
  4. 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. 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
  6. 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
  7. 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
  8. 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
  9. 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
  10. 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
      • 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….

        Reply
  11. 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
  12. 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
  13. 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
  14. 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
  15. 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
    • 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
  16. 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
  17. 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
  18. 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
  19. 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
  20. hello its is true this sensor can detect from 2cm – 4meter? and if distance over than 4meter, what will show at lcd display?

    Reply
  21. Thanks for the clear explanation. Still I dont understand. The counting starts when echoPin (input) gets the state HIGH (in this example). And the counting stops, when it gets the state LOW. Their time difference is 10us in the pingPin and their time difference is 10us in the echoPin. It is always the the same. The distance doesnt make any difference. The begin of the signal is moving as fast as the end of the signal. What actually starts the counting. It has to start, when the signal goes to pingPin. And it has to stop, when the signal come sback to echoPin. Would You please explain me more.

    Reply
    • Well according the code and the logic of the trigger and echo pins your are totally right to be confused, so I was, but here’s the trick:
      When we activate the trigger input (digitalWrite(trigPin, HIGH);), we send the ultrasound wave but at the same time, the sensor raises the echo pin internally. So the echo pin is already HIGH when the program gets to the pulseIn() function, which means the counting will depend on the objects distance.

      Reply
  22. Hi.
    I’m new at this but i was wondering. Is it mandatory to use a breadboard? Or I can connect the sensor directly to my Arduino UNO ?

    Thanks,
    Cris

    Reply
  23. Hello Dejan,

    Say for example I am measuring the volume difference in a container. How do I modify the code to measure volume instead.

    Thanks

    Reply
    • Hey, well you would need to measure three dimensions, width, length and depth and multiply them to get the volume. Check my Arduino Range Measurer project where I showed something similar, or how to measure area using this sensor.

      Reply

Leave a Comment