HC-SR04 Ultrasonic Sensor Interfacing with Arduino – Distance Measurement Example

This tutorial shows how to use HC-SR04 or HY-SR05 Ultrasonic sensors with Arduino for contactless distance measurement. First, we learn to interface  HC-SR04 or HY-SR05 with Arduino. After that, we will see example codes with or without Ultrasonic sensor Arduino library. Firstly, we will see an example to control an LED with an Arduino and Ultrasonic sensor. After that 16×2 LCD will be used to display distance (cm) measurement value. 

HC-SR04 with Arduino distance measurement

How to Interface HC-SR04 Ultrasonic sensor with Arduino 

To interface HC-SR04 ultrasonic sensor with Arduino, we should know the functionality of each pin of the ultrasonic sensor. By knowing the functionality of input and output pins, we will be able to identify which GPIO pins of Arduino should be used to interface with  HC-SR04. 

HC-SR04 Pin Details

The figure given below shows its pin configuration. It consists of four pins namely; Vcc, Ground, Trigger and Echo pin.

HC-SR04 Ultrasonic Sensor Pinout diagram

Vcc and Ground are used to power sensor. We should supply 5 volts to the Vcc pin and connect the GND pin with the ground terminal of the power supply. 

Trigger: It is an input pin. Trigger pin is used to initiate the ultrasonic sensor to start distance measurement or distance ranging. When users want to get distance measurements from the sensor, we apply a 10µs pulse to this pin.

Echo: This is a pulse output pin. The echo pin produces a pulse as an output. The width of pulse or on-time of the pulse depends on the distance between the ultrasonic sensor and obstacle which is placed in front of the HC-SR04 sensor. In idle conditions, this pin remains at an active low level. 

Further details on ultrasonic sensor working are provided in the next section. 

Working 

HC-SR05 ultrasonic sensor measures distance by using inaudible ultrasonic sound waves of 40KHz frequency. Like sound waves, ultrasonic waves travel through air and if there is any obstacle in front of them, they reflect according to their angle of incidence. Moreover, if an object is placed parallel to an ultrasonic transmitter, ultrasonic waves reflect exactly at an angle of 180 degree. Therefore, for distance measurement with HC-SR05 sensor, we place the object under test exactly in parallel position with ultrasonic sensor as shown in figure below. 

HC-SR04 and object distance position

HC-SR05 ultrasonic sensor consists of two basic modules such as ultrasonic transmitter and ultrasonic receiver module. The transmitter circuit converts an electrical signal into a 40KHz burst of 8 sonar wave pulses. The input electrical signal to the transmitter circuit is 10µs pulse input to the trigger pin of the HC-SR04 sensor. As we mentioned earlier, we apply this trigger input signal through Arduino or any microcontroller. On the other hand, the ultrasonic receiver circuit listens to these ultrasonic waves which are produced by the transmitter circuit. 

Measure HC-SR04 Echo Pulse Time with Arduino

Ultrasonic sensor HC-SR04 working
  • To start ranging with HC-SR04, first, we apply 10µs pulse to the trigger pin of the HC-SR04 sensor from the Arduino digital output pin.
  • As soon as 10µs input trigger signal becomes active low, the transmitter circuit produces a burst of 8 ultrasonic sonar pulses. At the same time, the Echo pin also makes a transition from a logic low level to a logic high level. 
  • When the Echo pin goes high, We start to measure time with the Arduino duration measurement function. 
  • These waves travel through the air and if there is any object placed in parallel to the sensor, these waves reflect back after a collision with the object. 
  • As soon as the ultrasonic waves received by the receiver circuit after striking with an object, the echo pin goes low. Arduino detects this transition of echo output signal from active high to an active low level and stops the measurement.  

In short, by measuring the on-time of the Echo output pulse signal,  we can measure the distance. The following figure illustrates the echo output signal with respect input trigger signal and 8 sonar pulses.

Timing diagram HC-SR04

The duration for which echo output signal remains high depends on the distance between the ultrasonic sensor and the object which we place in front of the sensor. Higher is the distance,  higher the time sonar waves will take to reach back to the ultrasonic receiver circuit. Because ultrasonic waves travel through air with the speed of sound and speed remains constant. 

How to Convert Time Duration into Distance

In the next section, we will see how to measure pulse duration using Arduino. Let’s assume that we have measured the output pulse on-time (t) with Arduino. Now the question is how to convert this measured time into distance.

Well, this is the most obvious part of this tutorial. In high school, we all study a well-known distance-time equation that is S = vt. We can convert the pulse duration (t) into the distance (S) using this equation.

Distance (S) = Speed (v) * t  //distance in meters

Here v is the speed of ultrasonic waves in air. The speed of ultrasonic waves in air is equal to the speed of sound which is 340 m/s (meter per second). 

The above equation will give distance output in units of meter. But, if you want the distance in centimeter units, multiply 340 with 100.  Hence, the above equation becomes:

S = 34000 * t   // distance in cm

The time given in the above formula should also be divided by two. Because ultrasonic waves travel from the transmitter to the obstacle and then reflect back to the receiver circuit by traveling the same distance. We want to find the distance between HC-SR04 and the object only. Therefore, the formula to calculate distance becomes :

S = 17000 * t    // distance in cm

Connection Diagram HC-SR04 and Arduino

Until now we have seen the working of the ultrasonic sensor and the pin details. Now we know that to interface an HC-SR04 sensor with Arduino, we need four pins out of which two are power supply pins and two are digital input output pins. One GPIO pin of the Arduino will be used as a digital output pin to provide a trigger signal to the ultrasonic sensor. Similarly, one GPIO pin will be used as a digital input pin to capture echo output signal of output sensor.  

HC-SR04 ultrasonic sensor interfacing with Arduino connection diagram

Now make the connection of the Arduino with the HC-SR04 sensor according to this connection diagram. In this schematic diagram, we use the D9 pin of Arduino to provide a trigger signal and D11 to capture the echo output pulse. 

HC-SR04Arduino
Vcc+5V
GNDGND
TriggerD9
EchoD11

Arduino Code for Ultrasonic Sensor with LED

In this example code, we will control an LED based on measured distance value. Arduino Uno has an onboard LED that is connected with the D13 pin. This code takes the distance measurement and if the measured distance value is less than 10cm, LED will turn on. Otherwise LED remains off.

/*
* Ultrasonic Sensor HC-SR04 interfacing with  Arduino 
*
* by microcontrollerslab.com
*/

/* Define the names for Arduino pin for HC-SR04*/
#define trigger_pin 9
#define Echo_pin 11
#define LED 13

/* two variables to store duraion and distance value */
long duration;
int distance;

/* configure D9 and D11 as digital input and output respectively */
void setup() {
pinMode(trigger_pin, OUTPUT); // configure the trigger_pin(D9) as an Output
pinMode(LED, OUTPUT); // Set the LED (D13) pin as a digital output
pinMode(Echo_pin, INPUT); // configure the Echo_pin(D11) as an Input
Serial.begin(9600); // Enable the serial with 9600 baud rate
}

void loop() {
  
digitalWrite(trigger_pin, LOW); //set trigger signal low for 2us
delayMicroseconds(2);

/*send 10 microsecond pulse to trigger pin of HC-SR04 */
digitalWrite(trigger_pin, HIGH);  // make trigger pin active high
delayMicroseconds(10);            // wait for 10 microseconds
digitalWrite(trigger_pin, LOW);   // make trigger pin active low

/*Measure the Echo output signal duration or pulss width */
duration = pulseIn(Echo_pin, HIGH); // save time duration value in "duration variable
distance= duration*0.034/2; //Convert pulse duration into distance

/* if distance greater than 10cm, turn on LED */
if ( distance < 10)
digitalWrite(LED, HIGH);
else 
digitalWrite(LED, LOW);
// print measured distance value on Arduino serial monitor
Serial.print("Distance: ");
Serial.println(distance);
}

How Code Works?

First, define the names of Arduino pins using #define preprocessor directives. This defines that D9 and D11 pins of Arduino are used to control trigger and echo pins of the HC-SR04 sensor. Similarly, the D13 pin is assigned the name “LED”. Hence, through the program, we will use these symbolic names instead of pin numbers.

#define trigger_pin 9
#define Echo_pin 11
#define LED 13

These two variables are declared to store duration and distance values.

long duration;
int distance;

Inside Setup()

In the Arduino program, we perform configuration and initialization settings inside the setup() function. In this code, we initialize trigger_pin and LED pins as digital output pins and Echo_pin as a digital input pin. Also, enable serial communication to send distance measurement data to Arduino serial monitor.

pinMode(trigger_pin, OUTPUT); // configure the trigger_pin(D9) as an Output
pinMode(LED, OUTPUT); // Set the LED (D13) pin as a digital output
pinMode(Echo_pin, INPUT); // configure the Echo_pin(D11) as an Input
Serial.begin(9600); // Enable the serial with 9600 baud rate

If you don’t know to configure GPIO pins of Arduino as a digital input or output pins, you can refer to these tutorials:

Main loop()

Code written inside the loop() function executes repeatdly. Hence, we perform distance measurement or other useful functions inside this main loop() function.

As you know that to enable the ranging of data from the HC-SR04 sensor, we provide a 10µs pulse to the trigger pin. Therefore, This segment of code provides a 10µs pulse to trigger pin. It will initiate the distance sample taking process.

digitalWrite(trigger_pin, LOW); //set trigger signal low for 2us
delayMicroseconds(2);

/*send 10 microsecond pulse to trigger pin of HC-SR04 */
digitalWrite(trigger_pin, HIGH);  // make trigger pin active high
delayMicroseconds(10);            // wait for 10 microseconds
digitalWrite(trigger_pin, LOW);   // make trigger pin active low

As soon as we apply 10µs pulse to the ultrasonic sensor, in response, it produces a 40KHz sonar waves and raised the Echo output signal to an active high state. The echo output signal remains active high until these sonar waves reflect back to ultrasonic transmitter. As soon as, receiver circuit received these wave, the echo output signal goes to active low level. Hence, this line measures the timer for which output signal remains in active high state.

duration = pulseIn(Echo_pin, HIGH); // save time duration value in "duration variable

In Arduino IDE, the pulseIn() function is used to measure the pulse duration and it returns the time duration output in microseconds. But the formula of distance-time relationship that we derived above works if both speed and time have same units in terms of time such as seconds, microseconds, or milliseconds. But in this equation, speed unit is centimeter per second.

S = 17000 * t // distance in cm

To convert speed into centimeter per microsecond, divide this equation with 10^-6. Now units of speed and time both are compatible with each other.

S = 0.017* t // distance in cm

Finally, this line converts the pulse duration into distance (cm).

distance= duration*0.034/2;

If-else conditional block checks either measured distance is less than or greater than 10cm. If it is greater than 10, turn on LED. Otherwise, LED remains turn off.

if ( distance < 10)
digitalWrite(LED, HIGH);
else 
digitalWrite(LED, LOW);

At the end, serial.print() function prints the measured distance on Arduino serial monitor.

// print measured distance value on Arduino serial monitor
Serial.print("Distance: ");
Serial.println(distance);

Video Demo

HC-SR04 Ultrasonic Sensor with LCD and Arduino

In this section, we will design a distance measurement meter using HC-SR04 ultrasonic sensor and Arduino. We will use a 16×2 LCD to display measured distance value.

In our previous tutorial, we posted an in-depth guide on 16xLCD interfacing with Arduino. You can refer to the article here:

Now make connections with LCD, HC-SR04 ultrasonic sensor and Arduino.

HC-SR04 Ulrasonic Sensor interfacing with Arduino and display distance on LCD
16×2 LCDArduino
D4 – D79, 10, 11, 12
E7
RS4
VEEPOT (Middle Leg)
VSSGround
VDD+5V
D++5V
D-Ground

Connections with Arduino and HC-SR04:

HC-SR04Arduino
Vcc+5V
GNDGND
TriggerD2
EchoD3

HC-SR04 Arduino Code

This distance measurement arduino code for hc-sr04 displays the value of distance on 16×2 LCD in units of centimeter.

/*
* Ultrasonic Sensor HC-SR04 interfacing with  Arduino 
*
* by microcontrollerslab.com
*/
// It inculde Liquid crystal display library in your code
#include <LiquidCrystal.h>
// This function assigns Arduino microcontroller about connection of LCD with Arduino. Pins should be connected in following manner :
// LiquidCrystal(RS, EN, D4, D5, D6, D7)
 LiquidCrystal lcd(4, 7, 9, 10, 11, 12);
/* Define the names for Arduino pin for HC-SR04*/
#define trigger_pin 2
#define Echo_pin 3
#define LED 13

/* two variables to store duraion and distance value */
long duration;
int distance;

/* configure D9 and D11 as digital input and output respectively */
void setup() {
pinMode(trigger_pin, OUTPUT); // configure the trigger_pin(D9) as an Output
pinMode(LED, OUTPUT); // Set the LED (D13) pin as a digital output
pinMode(Echo_pin, INPUT); // configure the Echo_pin(D11) as an Input
 lcd.begin(16, 2); // lcd.begin() function et up the LCD 16x2 LCD

}

void loop() {
  
digitalWrite(trigger_pin, LOW); //set trigger signal low for 2us
delayMicroseconds(2);

/*send 10 microsecond pulse to trigger pin of HC-SR04 */
digitalWrite(trigger_pin, HIGH);  // make trigger pin active high
delayMicroseconds(10);            // wait for 10 microseconds
digitalWrite(trigger_pin, LOW);   // make trigger pin active low

/*Measure the Echo output signal duration or pulss width */
duration = pulseIn(Echo_pin, HIGH); // save time duration value in "duration variable
distance= duration*0.034/2; //Convert pulse duration into distance

/* if distance greater than 10cm, turn on LED */
if ( distance < 10)
digitalWrite(LED, HIGH);
else 
digitalWrite(LED, LOW);
// print measured distance value on Arduino serial monitor
lcd.setCursor(0,0); // set the cursor position
lcd.print("Distance = "); //print the string on cursor position
lcd.print(distance);
lcd.print("cm");
}

Applications of Ultrasonic sensor HC-SR04

There are many applications of ultrasonic sensors from domestic use to industrial use. But some of them are given below :

  • Obstacle avoidance robot
  • Robotics
  • Object detection
  • Distance measurement
  • Liquid level monitoring system
  • Height measurement
  • Agriculture
  • Vehicle collision protection

Related Tutorials:

1 thought on “HC-SR04 Ultrasonic Sensor Interfacing with Arduino – Distance Measurement Example”

Leave a Comment