جامعــــــة البلقــــــاء التطبيقيـــــة
كليــــــة الذكاء االصطناعي
Embedded System
Arduino Lesson 2: Ultrasonic Sensor HC-SR04 and Arduino
1|Page
Mahmoud Al-Nuimat
Ultrasonic Sensor HC-SR04
In this tutorial we will learn how the HC-SR04 ultrasonic sensor works and how to use it with Arduino.
This is the most popular sensor for measuring distance and making obstacle avoiding robots with
Arduino.
Table of contents:
1. HC-SR04 Hardware Overview
2. HC-SR04 Ultrasonic Sensor Pinout
3. How the HC-SR04 Ultrasonic Distance Sensor Works?
4. How to Connect HC-SR04 Ultrasonic Sensor to Arduino
5. HC-SR04 Ultrasonic Sensor Arduino Code
1. Code Explanation
6. Arduino Ultrasonic Sensor and LCD Display Example
7. Example Code Using the NewPing Library
8. Improving HC-SR04 Distance Sensor Accuracy with DHT22 Temperature Sensor
1. Arduino code
9. HC-SR04 Dimensions and 3D Model
10. Conclusion
2|Page
Mahmoud Al-Nuimat
HC-SR04 Hardware Overview
The HC-SR04 is an affordable and easy to use distance measuring sensor which has a range from 2cm
to 400cm (about an inch to 13 feet).
The sensor is composed of two ultrasonic transducers. One is transmitter which outputs ultrasonic
sound pulses and the other is receiver which listens for reflected waves. It’s basically a SONAR which is
used in submarines for detecting underwater objects.
3|Page
Mahmoud Al-Nuimat
Operating Voltage 5V DC
Operating Current 15mA
Operating Frequency 40KHz
Min Range 2cm / 1 inch
Max Range 400cm / 13 feet
Accuracy 3mm
Measuring Angle <15°
Dimension 45 x 20 x 15mm
4|Page
Mahmoud Al-Nuimat
HC-SR04 Ultrasonic Sensor Pinout
Here’s the pinout of the sensor:
The sensor has 4 pins. VCC and GND go to 5V and GND pins on the Arduino, and
the Trig and Echo go to any digital Arduino pin. Using the Trig pin we send the ultrasound wave from
the transmitter, and with the Echo pin we listen for the reflected signal.
5|Page
Mahmoud Al-Nuimat
How the HC-SR04 Ultrasonic Distance Sensor Works?
It 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.
In order to generate the ultrasound we need to set the Trig pin on a High State for 10 µs. That will send
out an 8 cycle ultrasonic burst which will travel at the speed of sound. The Echo pins goes high right
away after that 8 cycle ultrasonic burst is sent, and it starts listening or waiting for that wave to be
reflected from an object.
If there is no object or reflected pulse, the Echo pin will time-out after 38ms and get back to low state.
6|Page
Mahmoud Al-Nuimat
If we receive a reflected pulse, the Echo pin will go down sooner than those 38ms. According to the
amount of time the Echo pin was HIGH, we can determine the distance the sound wave traveled, thus
the distance from the sensor to the object.
For that purpose we are using the following basic formula for calculating distance:
Distance = Speed x Time
We actually know both the speed and the time values. The time is the amount of time the Echo pin was
HIGH, and the speed is the speed of sound which is 340m/s. There’s one additional step we need to do,
and that’s divide the end result by 2. and that’s because we are measuring the duration the sound wave
needs to travel to the object and bounce back.
7|Page
Mahmoud Al-Nuimat
Let’s say the Echo pin was HIGH for 2ms. If we want the get the distance result in cm, we can convert
the speed of sound value from 340m/s to 34cm/ms.
Distance = (Speed x Time) / 2 = (34cm/ms x 1.5ms) / 2 = 25.5cm.
So, if the Echo pin was HIGH for 2ms (which we measure using the pulseIn() function), the distance
from the sensor to the object is 34cm.
8|Page
Mahmoud Al-Nuimat
How to Connect HC-SR04 Ultrasonic Sensor to Arduino
Here’s how we need to connect the HC-SR04 sensor to an Arduino board.
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.
You can get these components need for this tutorial from any of the sites below:
Components Needed:
Ultrasonic Sensor HC-SR04
Arduino Board
Breadboard and Jump Wires
9|Page
Mahmoud Al-Nuimat
HC-SR04 Ultrasonic Sensor Arduino Code
Here’s a code for measuring distance using the HC-SR04 ultrasonic sensor and Arduino.
Code Explanation
First we have to define the Trig and Echo pins. In this case they are the pins number 9 and 10 on the
Arduino Board and they are named trigPin and echoPin. Then we need a Long variable,
named “duration” for the travel time that we will get from the sensor and an integer variable for the
distance.
10 | P a g e
Mahmoud Al-Nuimat
// defines pins numbers
const int trigPin = 9;
const int echoPin = 10;
// defines variables
long duration;
int distance;
In the setup we have to define the trigPin as an output and the echoPin as an Input and also start the
serial communication for showing the results on the serial monitor.
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
In the loop first we have to make sure that the trigPin is clear so you have to set that pin on a
LOW State for just 2 µs. Now for generating the Ultra sound wave we have to set the trigPin on
HIGH State for 10 µs.
// Clears the trigPin
digitalWrite(trigPin, LOW);
11 | P a g e
Mahmoud Al-Nuimat
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
Using the pulseIn() function we read the travel time and put that value into the variable
“duration”. This function has 2 parameters, the first one is the name of the Echo pin and for the second
is the state of the pulse we are reading, either High or Low.
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
In this case, we need this set to it HIGH, as the HC-SR04 sensors sets the Echo pin to High after sending
the 8 cycle ultrasonic burst from the transmitter. This actually starts the timing and once we receive the
reflected sound wave the Echo pin will go to Low which stops the timing. At the end the function will
return the length of the pulse in microseconds.
For getting the distance we will multiply the duration by 0.034 and divide it by 2 as we explained this
equation previously.
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
At the end we will print the value of the distance on the Serial Monitor.
12 | P a g e
Mahmoud Al-Nuimat
Arduino Ultrasonic Sensor and LCD Display Example
Here’s another example how to use the ultrasonic sensor with Arduino and display the results on an
LCD.
You can connect the ultrasonic sensor and the LDC as following:
13 | P a g e
Mahmoud Al-Nuimat
The code measuring the distance is pretty much the same as the basic example. Here, instead of
printing the results on the serial monitor we print them on the LCD.
//Ultrasonic Sensor HC-SR04 and Arduino Tutorial
#include <LiquidCrystal.h>
LiquidCrystal lcd(1, 2, 4, 5, 6, 7); // Creates an LCD object. Parameters: (rs, enable, d4, d5, d6, d7)
const int trigPin = 9;
const int echoPin = 10;
long duration;
int distanceCm, distanceInch;
void setup() {
lcd.begin(16, 2); // Initializes the interface to the LCD screen, and specifies the dimensions (width and height)
of the display
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distanceCm = duration * 0.034 / 2;
distanceInch = duration * 0.0133 / 2;
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(distanceCm); // Prints the distance value from the sensor
lcd.print(" cm");
delay(10);
lcd.setCursor(0, 1);
lcd.print("Distance: ");
lcd.print(distanceInch);
lcd.print(" inch");
delay(10);
}
14 | P a g e
Mahmoud Al-Nuimat
Example Code Using the NewPing Library
There are actually a simpler and better way to program the Arduino to measure distance using the HC-
SR04 ultrasonic sensor, and that’s using the NewPing library.
In the previously explained code we manually triggered the sensor and measured the received signal
pulse duration. Then according to those results we calculated the distance based on it. Using the
NewPing library we can get the distance with just a single line of code.
Here’s an example code:
#include <NewPing.h>
#define TRIGGER_PIN 9
#define ECHO_PIN 10
#define MAX_DISTANCE 400 // Maximum distance we want to measure (in centimeters).
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
void setup() {
Serial.begin(9600);
}
void loop() {
delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between
pings.
int distance = sonar.ping_cm(); // Send ping, get distance in cm and print result (0 = outside set distance
range)
Serial.print("Distance: ");
Serial.print(distance);
Serial.println("cm");
}
It is much simpler than the previous example. We just use the call the ping_cm() method on the
NewPing sonar object and we get the distance in centimeters. If we want the distance in inches we can
use the ping_in() instead.
15 | P a g e
Mahmoud Al-Nuimat
The library also has few other useful features. For example, with the ping_median(iterations [,
max_cm_distance]) method, we can get more accurate results, as it returns a median, or the middle
value from several measurements. With the iterations parameter we set the number of samples the
program will take for calculating the middle value. The default value is 5 iterations.
The ping_median() returns the received pulse duration in microseconds.
Here’s an example:
Along the HC-SR04 ultrasonic sensor, we will use the DHT11 / DHT22 sensor to measure the
temperature and the humidity of the environment, and adjust the speed of sound value accordingly.
Arduino code
#include <NewPing.h>
#include "dht.h" // https://github.com/RobTillaart/DHTlib
#define TRIGGER_PIN 9
#define ECHO_PIN 10
16 | P a g e
Mahmoud Al-Nuimat
#define MAX_DISTANCE 400
#define dht22 5 // DHT22 temperature and humidity sensor
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
dht DHT; // Creats a DHT object
int readDHT, temp, hum;
float speedOfSound, distance, duration;
void setup() {
Serial.begin(9600);
void loop() {
delay(100);
// Read temperature and humidity from DHT22 sensor
readDHT = DHT.read22(dht22); // Reads the data from the sensor
temp = DHT.temperature; // Gets the values of the temperature
hum = DHT.humidity; // Gets the values of the humidity
17 | P a g e
Mahmoud Al-Nuimat
speedOfSound = 331.4 + (0.6 * temp) + (0.0124 * hum); // Calculate speed of sound in m/s
duration = sonar.ping_median(10); // 10 interations - returns duration in microseconds
duration = duration/1000000; // Convert mircroseconds to seconds
distance = (speedOfSound * duration)/2;
distance = distance * 100; // meters to centimeters
Serial.print("Distance: ");
Serial.print(distance);
Serial.println("cm");
So, first we are reading the temperature and humidity values from the DHT22 sensor, and then use
those values to calculate the speed of sound. Then we get the duration the sound wave travel in
microseconds, convert them to seconds and calculate the distance from the sensor to the objects in
centimeters.
Conclusion
So, we have covered pretty much everything that we need to know about using the HC-SR04 Ultrasonic
sensor with Arduino. It’s a great sensor for many DIY electronics projects where we need a non-contact
distance measuring, detection of presence or objects, level or position something etc.
18 | P a g e
Mahmoud Al-Nuimat