Blog  /  Arduino Ultrasonic Sensor-A Complete Guide on HC-SR04

Arduino Ultrasonic Sensor-A Complete Guide on HC-SR04

Are you thinking of giving your Arduino eyes or maybe spatial awareness? Just because you certainly don't want your robot to crash or fall off a table! Alternatively, perhaps you are thinking of making a parking sensor, a water level sensor, or a distance measuring device. However, you don't know how to begin?

You are at the right place! We will tell you exactly how you can achieve all of these purposes merely with a distance sensor. The HC-SR04 Arduino Ultrasonic Sensor is the second proximity sensor and is ideal for distance measurement and object/obstacle avoidance applications.

In this guide, we will tell you all about Ultrasonic Sensor and how it works with the Arduino microcontroller. We will assume that you are a beginner and will start explaining everything right from the basics.

 

1、Ultrasonic Sensor Arduino

1.1 What is Ultrasonic Sensor

An Ultrasonic Sensor is a module that calculates the distance from an obstacle/ body using sound waves. Its working phenomenon is to send out a sound wave traveling at an ultrasonic frequency and then hold-up until the body/object reflects the wave. After that, the time delay between the wave to transmit and then comes back is used for measuring the distance.

In other words, it is the time taken for the transmission and receiving of the sound wave. The following equation will further clarify your concept:

Now, you must be wondering why the distance has been divided by 2. It is because sound waves have a double space. That is first from the ultrasonic sensor and then again back to the sensor after reflection. So, to calculate how far the object is, we should divide the distance by 2.

 

Image 1: Arduino Ultrasonic Sensor

 

1.2 What is HC-SR04 Ultrasonic Sensor

 

HC-SR04 is an excellent Ultrasonic Sensor Arduino and is quite popular among the coders. Like what bats do, HC-SR04 utilizes SONAR to measure how far an object is from a subject entity. It features highly accurate and outstanding non-contact range detection.

HC-SR04 gives stable readings and has a compact shape and design that is easy to use. You can buy it according to your ease, with package length ranging from 2 cm to 400 cm. The best part is, sunlight or black material cannot affect its working. Still, it can be challenging to detect soft materials such as clothes.

Once you get hands on it, you can easily observe that it includes an individual ultrasonic receiver and a transmitter module. Figure 1 shows the HC-SR04 module that will get from the market. The ultrasonic transmitter module sends sound waves, which travel through the medium, and then the object reflects it. These bounced back the ultrasonic receiver module receives sound waves.

Just like a primary ultrasonic sensor, you can then measure the distance of an object from the subject entity. All you need is the time delay between the wave transmission and coming back to the sensor. You can use this sensor in many projects such as wall obstacle robot, obstacle avoidance robot, and distance measuring device.

 

Image 2: Arduino Ultrasonic Sensor

 

2、Arduino Ultrasonic Sensor Connection

 

 

2.1 What are the Pins of HC-SR04 Arduino Ultrasonic Sensor

 

Before beginning any project, you will always need to connect the ultrasonic sensor with the Arduino microcontroller. You can buy any Arduino microcontroller from the market, such as Arduino UNO, Arduino Mega, an Arduino nano. Figure 2 shows the Arduino microcontroller UNO board. It is straightforward to connect HC-SR04 with an Arduino since it only contains four pins. If you can understand the simple working principle behind these four pins, you are good to go.

HC-SR04 comes with the following four pins:

• VCC. That supplies the 5 V needed for the correct operation of the sensor.

• GND. That is the ground pin.

• Trig. It is the Trigger pin, and it sends out the sound waves.

• Echo. It is the Receiving pin which receives the bounced back sound waves.

The key features that you should note are:

• The module requires an operating voltage of is 5V DC.

• Operating Current of the module is 15mA.

• It measures with measuring the angle of 15°.

• It is capable of measuring distance ranging from 2cm to 4m.

 

2.2 How to connect HC-SR04 with Arduino microcontroller

 

 

In this section, we will tell you how you can connect HC-SR04 with the Arduino microcontroller. Again, the task is quite simple. Vcc, the supply pin, is always associated with a 5V pin of Arduino. GND, the ground pin, is always connected with the ground pin of Arduino. For the Trigger and Echo pin, it is still up to you how you want to connect them with Arduino.

However, keep in mind that you should always connect the Trigger and Echo pin to the digital pins of Arduino. In our example, the Trigger pin is connected to Pin 11, and the Echo pin is connected to Pin 12 of Arduino.

Before moving forward to how you can code on Arduino microcontroller to make this sensor work with your projects, we will introduce you to the NewPing library of Arduino in the next chapter.

 

Image 3: Arduino Ultrasonic Sensor

 

3、Arduino Ultrasonic Sensor Library

 

 

3.1 What is the NewPing Library?

 

 

If you are not familiar with NewPing Library, you are going to get in lots of trouble. You may feel that the newly installed ultrasonic sensor is not performing well because you don't know that the problem is not the ultrasonic sensor but the current ping and ultrasonic library.

The NewPing library is a gift from Arduino, which completely fixes any problems. It gives many new features, and a new life emerges in your ultrasonic Arduino sensors.

 

3.2 How to download the NewPing Library?

 

 

You can download the library here: Download NewPing Library.
After downloading it, just put the "NewPing" folder in the Arduino libraries folder "libraries\." At this point, we expect from you that you have already downloaded the Arduino IDE, and you know how to go to its library folder. The Arduino IDE is software for coding Arduino microcontroller projects.

After you are done with copy and paste the "NewPing" folder, open Arduino IDE, create a new sketch file, or you can also open an old one. Go to the menu bar and select "Sketch->Include Library->NewPing." Now you are all set to begin the coding of your project. Figure 3 shows the "include library" option.

 

Image 4: Arduino Ultrasonic Sensor

 

4、Ultrasonic Sensor Arduino Example Project

 

 

4.1 Distance Measurement Project

 

 

With this project, our sole aim is to let you know how HC-SR04 can measure the distance from an object. By thoroughly understanding the source code of this project, you can easily alter it to use with your projects.

 

4.2 What Components are Required

 

 

First of all, you will need an Arduino board, an ultrasonic sensor, a breadboard, and jumper wires. It sounds easy. Moreover, the NewPing library will further make your life easier and happier. In our example, we have connected the HC-SR04 with the Arduino microcontroller, as shown in Table 1. You can also solder the pins of HC-SR04, as shown in Figure 4.

 

Image 5: Arduino Ultrasonic Sensor

 

Also, it suggested that in the connection, you should keep in mind the following points:

• Please do not put the ultrasonic sensor on a metal surface as it can result in a short circuit. Moreover, what happens in a short course? High current flows through the circuit and which, in this case, may burn your sensor.

• For ease in mounting the ultrasonic sensor, you should cover the backside of the sensor with electrical tape. We highly recommend this step.

• Also, it is not necessary to mount the Ultrasonic sensor on a breadboard first. You can openly connect the sensor with the Arduino microcontroller using only the jumper wires.

Once you have connected the circuit as suggested, you are all set to go to the next chapter. In the next chapter, we have provided the source code and the explanation of our example project.

 

Image 6: Arduino Ultrasonic Sensor

 

5、HC-SR04 Ultrasonic Sensor Arduino Code

 

 

5.1 Source Code of Distance Measurement Project

 

 

The following code is the most straightforward code that you can get with the NewPing library. After you have installed the NewPing library, you can copy and paste this code into Arduino IDE. From there, you can upload it to your Arduino board. We hope that you already know how to upload code to an Arduino board. In the next sub-section, we have explained it thoroughly.

/*
* created by http://playground.arduino.cc/Code/NewPing
*/

#include

#define TRIGGER_PIN 9

#define ECHO_PIN 10

#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");

 

5.2 Explanation of Source Code of Distance Measurement Project

 

 

The NewPing library makes it pretty simple to measure the distance from an object. The first line of the code adds the NewPing library functionalities, so you should start coding.

Include the library by following the steps mentioned in Chapter 3:

#include

The next thing that you need to do is to declare or define the trigger and echo pin. You can freely choose any Arduino pin to connect with your sensor, provided that it is a digital pin. In our example, we have connected the Trigger pin with digital pin 9 of Arduino, and the Echo pin is connected with digital pin 12 of Arduino.

#define TRIGGER_PIN 11

#define ECHO_PIN 12

After that, to use the library, you must set the value of the maximum distance. For this purpose, define the MAX_DISTANCE variable.

#define MAX_DISTANCE 200

Next, you need to create a "NewPing instance" known as sonar:
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

Then for serial communication, we have initialized it in the setup() with a baud rate of 9600.

Serial.begin(9600);

Now, in the loop() function, to acquire the value of distance, you only need to use the ping_cm() attribute. This attribute belongs to the sonar object of the NewPing library. As a result, you will get the distance from the item in centimeters. In our example, we have defined the space to be a variable of integer type and is non-negative. Furthermore, if you are not comfortable measuring distance in centimeters, you can also measure it in inches. Simply use sonar.ping_in() to get the distance value in inches.

unsigned int distance = sonar.ping_cm();

Finally, we have printed the results to the serial monitor using the print() and published In() functions of Arduino IDE.

Serial.print(distance);

Serial.println("cm");

To further clarify how Arduino can make your life easier and comfortable, Figure 5 demonstrates the work that your Arduino microcontroller will be doing in this project. If it had not been Arduino, you would have to do it manually.

 

5.3 Source Code of Distance Measurement Project with LCD

 

 

If you want to display the values of distance on an LCD screen, you can do use the following new code. This code is simple alteration of previous code.
#include

#include // includes the LiquidCrystal Library

LiquidCrystal lcd(1, 2, 4, 5, 6, 7);

#define TRIGGER_PIN 9

#define ECHO_PIN 10

#define MAX_DISTANCE 200

// NewPing setup of pins and maximum distance
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {Serial.begin(9600);lcd.begin(16,2);}

void loop() {

delay(50);

unsigned int distance = sonar.ping_cm();

Serial.print(distance);

Serial.println("cm");

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(distance); // Prints the distance value from the sensor
lcd.print(" cm");

delay(10);

 

5.4 Explanation of Source Code of Distance Measurement Project with LCD

 

 

Again, this code is straightforward to understand. We will only mention the alterations that have been done to the previous code. First of all, include the LiquidCrytal library. After that, you will need to create an LCD object. It will initialize the reset, enable, d4, d5, d6, and d7 pins/parameters of LCD.

LiquidCrystal lcd(1, 2, 4, 5, 6, 7);

Then you need to initialize the LCD screen's interfaces. Also, mention the size (width and height) of the LCD. This should be done in the setup(). In our example, the LCD is a 16x2 type, so we have initialized it like:

lcd.begin(16,2);

Next, define the location on the screen where you want to display the text. This is simple; you only need to set the cursor:

LCD.setCursor(0,0);

For printing the value of distance, use the print() function of the LCD object.

LCD.print("Distance: ");

lcd.print(distance);

lcd.print(" cm");

 

Image 7: Arduino Ultrasonic Sensor

 

6、Conclusion

 

 

Now, we are hopeful that you are all set to begin coding new projects. Our main aim was to provide you with a complete guide on Arduino Ultrasonic Sensor. You don't need to visit different websites to know-it-all because we have thoroughly covered everything.

Your mind must be bursting with new ideas that can all be put into action now. You will also agree that HC-SR04 is indeed the best affordable ultrasonic sensor that is currently available in the market. Buy one and surprise us with your fantastic project ideas.

We can also help if you are looking for ideas about which project you should make with the ultrasonic sensor. You can try building a digital parking sensor with an integrated alarm system. Display the values of the distance of the car from an object and set off an alarm if the vehicle is getting too close.

Furthermore, if you still need more help or want to ask something, we are always here for you. Just contact us at sales@ourpcb.com or visit our website to get the best customer support. Our team of Engineers will be so glad to help you out with your projects.