Ultrasonic distance meter with LCD display on Arduino UNO

Introduction

In this tutorial we will see how to make an ultrasonic distance meter. Ultrasounds are acoustic waves having a frequency higher than that audible by humans. The medium crossed by the ultrasounds conditions its propagation speed. They are slower in gaseous media and faster in solid media. In air the speed of propagation is about 340 m/s. They are generally used in the medical field (echography), in non-destructive testing, in robots to identify obstacles or, as in our case, to measure distances.

In our project we will use an HC-SR04 ultrasonic module for distance measurement which will then be displayed on a 2-line, 16-character LCD display.

If your LCD display doesn’t have the 16-pin connector soldered and you don’t know how to do it, our tutorial Yet another tutorial on how to solder may be for you.

The maximum distance measured by the HC-SR04 is about 4 meters, the minimum is 2 cm with an accuracy of 3 mm. We have also foreseen the use of a piezoelectric buzzer that sounds when the distance becomes greater than 4 meters (and therefore no longer measurable by the module).

Two more things necessary if you want to make more accurate measurements:

  • a bubble level
  • a laser pointer

Unfortunately, during our testing phases, we discovered that this device cannot be powered with a common 9V battery because it is not able to supply all the necessary current. So the distance meter must necessarily be powered connected to the USB socket of a PC or to a wall power supply (or perhaps with a battery that supplies much more mA/h than the classic 9V).

The following video shows how our ultrasonic distance meter works:

How the ultrasonic distance meter works

What components do we need?

The list of components is not particularly long:

  • a breadboard to connect the Arduino UNO board to the other components
  • some DuPont wires (male – male, male – female, female – female)
  • a HC-SR04 module
  • 2 10kΩ resistors
  • a 10kΩ potentiometer
  • a 2 x 16 LCD display
  • a 2N3904 transistor (or a 2N2222)
  • a push button switch
  • a piezoelectric buzzer
  • and, of course, an Arduino UNO board!

We also need the sketches to upload to the Arduino which we can download from the following link:

What is the working principle of the distance meter?

The system transmits a train of ultrasonic frequency pulses towards the object and receives the echo. Based on the reflection time (i.e. the time the impulse takes to go towards the obstacle and back), Arduino calculates the distance using the following formula:

Distance = (time to go to obstacle and back × speed of sound) / 2

As already mentioned, the speed of sound in air is equal to 340m/s

Let’s see some pictures of the completed project:

Our ultrasonic distance meter without the paper tubes
Our ultrasonic distance meter without the paper tubes

Another picture of our distance meter
Another picture of our distance meter

How is the tutorial organized?

As usual we will proceed step by step:

  • initially we will see how to connect to Arduino and operate the HC-SR04 module
  • we will then add a button to perform the measurement
  • finally we will complete the project with the addition of the LCD display and the piezoelectric buzzer

Let’s connect the HC-SR04 ultrasonic module to Arduino

Let’s start by connecting the HC-SR04 module to Arduino as shown in the following Fritzing diagram:

The Fritzing wiring scheme
The Fritzing wiring scheme

The HC-SR04 module does not require any library. You simply have to connect it to the Arduino following the Fritzing diagram above or the following table:

  • 5V —-> Vcc
  • GND —-> GND
  • pin 7 —-> Trig
  • pin 8 —-> Echo

Loading code

At this point, download the attached ultrasonic.ino sketch (eliminate the .txt extension if present) and double-click on it. The Arduino IDE will ask you to save the new sketch in a folder whose name is the same as used for the .ino file. Save it wherever you like.

Setup function

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

int triggerPort = 7; 
int echoPort = 8;

To make the HC-SR04 module transmit a train of 8 pulses at a frequency of 40kHz, Arduino sends a pulse of 10us duration to pin 7.
In the setup function we define the two pins as OUTPUT and INPUT:

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

Loop function

The first four functions in the loop command the HC-SR04 module to transmit ultrasound 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);

To send a 10us pulse to the triggerPort, Arduino sets pin 7 to the HIGH state. After this instruction, the sketch waits 10us before setting pin 7 back to LOW.
In the first lines of the following code, Arduino receives the reflection time of the ultrasonic wave measured by the HC-SR04 module. This time is used to calculate the distance using the formula

Distance = (time to go to obstacle and back × speed of sound) / 2

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 calculate if the object is too far away, determining 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 the sketch in the screenshot below:

The serial monitor shows the measurements
The serial monitor shows the measurements

Let’s add a button

Update the wiring by adding the button according to the following scheme:

The Fritzing wiring scheme
The Fritzing wiring scheme

Obviously we want our distance meter to take measurements only when necessary. We can implement this feature simply by adding a button. Then, by pressing the button, the Arduino and the HC-SR04 module will start making measurements.
Look at the Fritzing diagram above to see how to wire the button. Remember that a 10kΩ resistor is also required for this connection.
The first step is to declare the pin used to detect the state of the button (we chose pin 10):

#define BUTTON 10

So, let’s set this pin as an INPUT, in the setup function:

pinMode(BUTTON, INPUT);

The last statement must be placed in the loop function:

while(digitalRead(BUTTON) == LOW);

But what function does the previous instruction perform?
When the button is not pressed, the logical condition in the while loop is TRUE, therefore the sketch remains indefinitely inside the loop and does not execute subsequent lines.
Conversely, when the button is pressed, the logical condition becomes FALSE and the sketch exits the while loop, thus executing the next lines and starting the measurement. As you can see for yourself, the serial monitor shows measurements only if the button is pressed.
The complete ultrasonic_and_button.ino sketch is attached (remove the .txt extension if present).

Let’s connect an LCD display and a piezoelectric buzzer

It’s time to connect the LCD display to the Arduino. As already seen in the introduction, you will also need other components: a 2N3904 transistor (or the equivalent 2N2222), a 10kΩ resistor, a 10kΩ linear potentiometer to adjust the contrast. We use these components to make the backlight of the LCD display turn on when we press the button. Follow the Fritzing scheme below to update the links:

The Fritzing wiring scheme
The Fritzing wiring scheme

Since pin 7 is now used by the display, we changed the pin used by the HC-SR04 module by connecting it to pin 9.

Another useful component is the piezoelectric buzzer that sounds when the object is too far away.

Note: we will not explain how to connect an LCD display to Arduino and how to control the backlight because these topics have been covered in the Thermo-hygrometer with clock and LCD display on Arduino UNO tutorial.

The sketch

Let’s now adapt the sketch to implement the changes we want to implement. In the first part of the sketch we have to declare two constants and one variable.
The first constant defines the PWM pin used to turn the display backlight on and off and the second defines the note that the piezoelectric buzzer will emit when the object is too far away.
The variable instead sets the brightness of the backlighting to the maximum value:

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

Now let’s include the LiquidCrystal library and initialize it:

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

In the setup function we have to declare pin 11 as OUTPUT and initialize the LCD display (16 columns and 2 rows):

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

Loop function

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

while(digitalRead(BUTTON) == LOW) 
{ 
    analogWrite(LUMIN, 0); // turn LED off 
    lcd.clear();     
    noTone(12); 
}

When the button is not pressed, the logical condition is TRUE, consequently the sketch waits in the while loop. In this situation, the first line in the block turns off the backlight, the second clears the display screen, and the third turns off the tone generator that drives the piezoelectric buzzer.
Instead, when the button is pressed, the logical condition becomes FALSE and Arduino skips the while loop and executes the following line…

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

…which turns on the backlight.
Since we no longer use the serial monitor but the LCD display, we need to change the Serial.print functions to lcd.print:

lcd.setCursor(0, 0); 
lcd.print("time: "); 
lcd.print(duration); 
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);
}

The first line of the display shows the thinking time while the second line shows the calculated distance. If the reflection time is greater than 38ms, the obstacle is out of range and the piezoelectric buzzer emits a note while the display shows the message “out of reach”, otherwise the sketch shows the measured distance.
The complete ultrasonic_button_lcd_buzz.ino sketch is attached (remove the .txt extension if present).

Tests and measurements

In order to use the device easily, we placed the components on a 24×8 cm wooden board. We also used two different breadboards: a mini one for the ultrasound module and the button and a medium one for the other components.
We have also installed two essential objects to increase the accuracy of the measurements: a simple laser pointer and a spirit level.
A last very useful addition consists of a pair of paper tubes (each 7.5cm long) that we have placed in front of the transducers of the ultrasound module. These tubes are needed to focus the pulses emitted by the module which would otherwise diverge excessively. In fact, if you check the module datasheet, you can see that the measurement angle is 15 degrees.
During our tests we realized that the tubes are necessary for “long distances” (greater than one meter) while they can give rise to false measurements if used for shorter distances.
The maximum distance that was possible to measure is 418cm.

Measurements performed with the ultrasound module and measuring wheel
Measurements performed with the ultrasound module and measuring wheel

Measurement operations
Measurement operations

Measurement operations
Measurement operations

To improve the directionality of the ultrasonic sensor, we used two paper tubes. We have noticed that in this way the measurement is more precise since the ultrasounds are better directed and therefore do not bounce off lateral objects that we are not pointing at:

The paper tubes
The paper tubes

Detail of the LCD display
Detail of the LCD display

Measurement close to the maximum range
Measurement close to the maximum range

As you can see the device is very accurate
As you can see the device is very accurate

Measurement beyond the maximum limit (4.1m)
Measurement beyond the maximum limit (4.1m)

Final considerations

The most immediate use of this distance meter is to measure the distance of an object. A possible alternative use could be as a parking sensor: it would be enough to install it on the wall of our garage and modify the function that makes the buzzer sound so that it sounds when the obstacle (in this case the car) is too close.

Newsletter

If you want to be informed about the release of new articles, subscribe to the newsletter. Before subscribing to the newsletter read the page Privacy Policy (UE)

If you want to unsubscribe from the newsletter, click on the link that you will find in the newsletter email.

Enter your name
Enter your email
0 0 votes
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
Scroll to Top