Ultrasonic Distance Meter With LCD Display on Arduino UNO




Introduction: Ultrasonic Distance Meter With LCD Display on Arduino UNO

In this tutorial we are going to see a different use of the HC-SR04 ultrasonic module. This module is often used on robots and toy cars to locate obstacles but it can be used to measure distances as well.

Distances measured by the HC-SR04 will be shown on our beloved LCD 16x2 display. Take a look at our tutorial if you want to know how to solder a pin header to this kind of display.

The maximum range of HC-SR04 is 4 meters, and the shortest measurable distance is 2cm with an accuracy of 3mm. We made a piezoelectric speaker ring when the distance meters goes out of reach.

Other two things are required if you want your distance meter to do more accurate measurements:

  1. A spirit level
  2. A laser pointer

Unfortunately, while making tests we discovered this device can't be powered by a 9V battery because of a lack of energy (in terms of supplied Ampere). So, you have to supply your distance meter by using a computer or an AC adapter (yes, it's not handy at all, but this is just an experiment!)

Shopping list:

  • Arduino UNO
  • USB cable
  • The Arduino IDE installed on your PC
  • Set of Dupont cables
  • MB-102 breadboard
  • An HC-SR04 ultrasonic sensor
  • LCD 16x2 display
  • 10k Ohm linear potentiometer
  • 2N3904 transistor (or a 2N2222)
  • Number 2 10k Ohm resistor (1/4 Watt)
  • Push-button
  • Piezoelectric buzzer

How does it works?

The system transmits a burst of ultrasonic sound waves towards the subject and then receives the corresponding echo. According to the reflection time, Arduino calculates the distance thanks to the following formula:

Test distance = (high level time × speed of sound*) / 2

    *speed of sound in air is 340m/s

    Step 1: Connecting HC-SR04 Ultrasonic Module to Arduino

    HC-SR04 wiring

    The HC-SR04 module doesn't need any extra library. You just have to connect it to Arduino following the attached Fritzing drawing or the scheme below:

    5V ----> Vcc

    GND ----> GND

    pin 7 ----> Trig

    pin 8 ----> Echo

    Uploading the code
    Now, download the file ultrasonic.ino and then double click on it. Arduino IDE will ask you to save the new sketch into a folder whose name will be the same one used for the .ino file. Save the file where you prefer.

    Setup function

    At the beginning of the sketch, we define the two pins used for trigger and echo:

    int triggerPort = 7;
    int echoPort = 8; 

    In order to make the HC-SR04 transmit a burst of 8 ultrasound waves (40kHz), Arduino sends a pulse (10us) to the pin 7.

    Into the setup function, we properly set them as OUTPUT and INPUT:

    pinMode( triggerPort, OUTPUT );
    pinMode( echoPort, INPUT ); 

    Loop function

    The first four instructions into the loop allow the HC-SR04 to transmit microwaves towards an object:

    digitalWrite(triggerPort, LOW);			// set to LOW trigger's output
    digitalWrite(triggerPort, HIGH);		// send a 10us pulse to the trigger
    delayMicroseconds( 10 );
    digitalWrite(triggerPort, LOW); 

    By sending a 10us pulse to the triggerPort, Arduino sets the pin 7 to HIGH. After this instruction, the sketch waits 10us before setting the pin 7 LOW again.

    In the first line of the following instructions, Arduino receives the reflection time of ultrasonic waves from the HR-SR04. This time is needed to calculate the distance by using the formula distance = (high level time × speed of sound*) / 2 shown in the second line.

    long duration = pulseIn(echoPort, HIGH);
    long r = 3.4 * duration / 2;			// here we calculate the distance
    float distance = r / 100.00;

    The last lines determine if the object is too far, checking if the reflection time is greater than 38ms.

    if( duration > 38000 ) Serial.println("out of reach");		
    else { Serial.print(duration); Serial.println("cm");} 

    You can see the output of this sketch in the screen-shot attached above.

    Step 2: Adding a Pushbutton

    Of course, we want our distance meter to do measurements only when we need. We can simply implement this feature adding a push-button. So, pressing a bush-button, Arduino and HC-SR04 do a measurement.

    See the attached Fritzing scheme to see how to connect the push-button. Remember that a 10k Ohm resistor is required for this wiring.

    The first step is to declare the pin used to connect the button (we chose the pin 10):

    #define BUTTON 10  

    Then, into the setup function, we set this pin as an INPUT:

    pinMode(BUTTON, INPUT); 

    The last instruction has to be put into the loop function:

    while(digitalRead(BUTTON) == LOW); 

    What does the previous instruction do?

    When the push-button isn't pressed, the logical condition inside the while cycle is TRUE, so the sketch stays endlessly inside it and will not execute the next lines.

    On the contrary, when the push-button is pressed, the logical condition becomes FALSE and the sketch comes out from the while loop and executes the following lines doing a measurement.

    As usual you can download the ready to use sketch.

    As you can see if you test this step, the serial monitor will show measurements only when the push-button is pressed.

    Step 3: Connecting a Lcd Display and a Piezoelectric Buzzer

    Now it's time to connect the LCD display to our Arduino. As seen in the Introduction, you'll also need some other things to make this circuit: a 2N3904 transistor (or, alternatively, a 2N2222), a 10k Ohm resistor, a 10k Ohm linear potentiometer for adjusting the contrast. These components are needed to make the LCD display turn on when pressing the push-button during measurements.

    Furthermore, adding a piezoelectric speaker can be a wise choice if you want to be informed when the distance meter goes out of reach.

    NOTE: we are not going to explain how to connect an LCD display to Arduino as well as how to control its back-light because these procedures have been already explained in the fifth and sixth steps of our previous tutorial respectively.

    But if you are only interested in doing the connections, just see the attached Fritzing scheme.

    NOTE: Since the pin 7 is now used by the display, we changed the pin used by the HC-SR04 moving it to the pin 9.

    The sketch

    Let's adapt the sketch according to the changes we want to make.

    In the first part of the sketch, we have to declare two constants and a variable. The first constant is the PWM pin used to turn on and off the display back-light and second one is the frequency of the note played by the piezo speaker when the distance meter goes out of reach.
    The variable is needed to set the back-light brightness up to the maximum value.

    #define LUMIN 11
    #define NOTE_A4 440
    int l = 255; 

    Then we include the LiquidCrystal library and initialize the LCD display library:

    // include the library code:
    #include <LiquidCrystal.h>
    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(2, 3, 4, 5, 6, 7);

    Setup function

    Into the setup function we need to declare the pin 11 as an OUTPUT and initialize the LCD display (16 columns and with 2 rows):

    pinMode(LUMIN, OUTPUT);
    // set up the LCD's number of columns and rows: 
    lcd.begin(16, 2); 

    In the loop function we make some changes. First of all we modify the while loop as shown below:

    while(digitalRead(BUTTON) == LOW) {             
      analogWrite(LUMIN, 0);  // turn LED off 

    When the button is not pressed down, the logical condition is TRUE, as a consequence the sketch waits into this while loop. In this situation, the first line in the block turns the back-light off, the second line clears the display and the third one turns the tone generator off.

    When the push-button is pressed, the logical condition becomes FALSE and Arduino skips this while loop and goes on executing the following line...

    analogWrite(LUMIN, l);  // turn LED on

    ...which turns the backlight on.

    As we are not using the serial monitor any more, we have to change the functions Serial.print to lcd.print.

    lcd.setCursor(0, 0);
    lcd.print("time: ");
    lcd.print(" us    ");
    lcd.setCursor(0, 1); 
    if( duration > 38000 ) {lcd.println("out of reach    "); tone(12, NOTE_A4);}		
    else { lcd.print("dist: "); lcd.print(distance); lcd.println(" cm    "); noTone(12);}

    In the first row the display it prints the reflection time and the distance in the second one. If reflection time is greater than 38ms, the obstacle is out of reach and the piezo buzzer will play a sound and the display will show the message "out of reach", otherwise the sketch will print the measured distance.

    As usual, the sketch is ready to be downloaded.

    Step 4: Measurement Tests

    In order to make the device easier to use, we placed the components on a 24x8cm wooden board. We also used two different breadboards: a mini breadboard for the ultrasonic module and the pushbutton, and a medium size breadboard for the other components.

    In addition, we installed two essential things to do more accurate measurements: a simple laser pointer and a tubular spirit level.

    The last useful thing is a couple of paper pipes (ours are 7.5 cm long) which have to be placed in front of the two speakers of the ultrasonic module. They are required in order to focus the ultrasonic pulses coming out from the ultrasonic module speakers, which otherwise would diverge excessively. In fact, according to the datasheet, the measuring angle is 15 degrees.

    While doing measurements, we discovered that the pipes are required for "long distances" (greater than 1 meter) and misleading for short ones.

    The longest distance we did has been 418cm.

    5 People Made This Project!


    • Pocket-Sized Speed Challenge

      Pocket-Sized Speed Challenge
    • Super-Size Speed Challenge

      Super-Size Speed Challenge
    • Audio Challenge 2020

      Audio Challenge 2020

    17 Discussions


    2 months ago

    thank you, it work


    1 year ago

    and what is the cost of all of that?


    3 years ago

    I followed it step by step but the lcd wont even light up? I don't know why it doesn't work. p.s I'm pretty much brand new to arduino.


    2 years ago

    but can i change the function of the buzzer imean can i use it for measuring the closest distance like 50cm

    how? need it for this project

    pravin jag
    pravin jag

    2 years ago

    Hello there is some problem in code I face the problem of constructor and distructor and type of conversation. Please give me solution for this.


    3 years ago

    Would it work if i use 1/6 watt 10k resistors instead of 1/4 watt 10k resistors?


    Reply 3 years ago



    3 years ago

    How connect the laser diode and what should I add to code to light like a pointer when i press the push button ?


    4 years ago

    hey there

    which software you use for simulation?

    any one know?

    Vadiraj Kerur
    Vadiraj Kerur

    4 years ago

    Sir can we have an option of 2 ultrasonic sensor in one arduino with a lcd display showing the distance from both the sensors?
    If possible pls mail it to me( circuit and arduino program)......


    4 years ago

    Hi ArduinoR,

    thank you for your suggestion

    we made this solution for simplicity


    5 years ago on Introduction

    Hi Komal, we did it on the first step of this tutorial :)


    5 years ago on Introduction

    This is awesome! How would you make this accurate on further distances? Or is that just a limitation of the ultrasonic sensor do you think?


    Reply 5 years ago on Introduction

    This sensor works best at lower distances, which is kind of sad, as it would be awesome to meet how long it is to the neighbors house ;) Have great one,



    Reply 5 years ago on Introduction

    Thanks to those paper tubes, we could measure distances up to 4 meters without big problems. Of course, it also depends on materials whose target objects are made of: for example, walls reflect sound waves better than carpets because of their different absorption coefficient. Furthermore, pay attention to the position of paper tubes: they must be parallel if you want to do accurate measurement. Thanks for you comments, ciao!

    Just4Fun Media
    Just4Fun Media

    5 years ago

    Interesting build. I played around with ultrasonic a while back.

    It can get more accurate but it can also get crazy expensive as it is effected by humidity, temperature, and altitude. So there are a lot of sensors to use to calibrate your readings.

    Have a great day!