Ultrasonic Sensor HC-SR04 and Arduino

In this Arduino Tutorial we will learn how the HC-SR04 Ultrasonic Sensor works and how to use it with the Arduino Board. The following video shows the results of this project read the tutorial below for more details.


The Ultrasonic Sensor 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.

The speed of sound is approximately 341 meters (1100 feet) per second in air. The ultrasonic sensor uses this information along with the time difference between sending and receiving the sound pulse to determine the distance to an object. It uses the following mathematical equation:

Distance = Time x Speed of Sound divided by 2

Time = the time between when an ultrasonic wave is transmitted and when it is received
You divide this number by 2 because the sound wave has to travel to the object and back.

When you have finished reading this tutorial, you will be familiar with:

  • Connecting and using HC-SR04 Ultrasonic Sensor
  • Connecting and using a I2C LCD

What You Will Need

We will need the following parts and libraries in this tutorial:



The following libraries will be used in this tutorial. Please refer to this tutorial on how to add an Arduino library in eclipse

We will be using Eclipse for Arduino, if you haven’t setup please refer to my previous tutorial on eclipse for Arduino.

Circuit Schematics

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.

Source Code

First we need to include the NewPing library which can be downloaded from here, then define the pin numbers to which the TRIGER and ECHO pins are connected and create a NewPing object. We also have to add the I2C library and initialize it in order to print the results. Using the ping_cm(function we will read the data from the sensor and put the values of the distance of the blocking object into the distance  variables. At the end we will print the distance value on the LCD.