ESP32 with HC-SR04 Ultrasonic Sensor with Arduino IDE
Learn how to use HC-SR04 Ultrasonic Sensor with the ESP32 board using the Arduino core. The ultrasonic sensor uses sonar to determine the distance to an object.
- Suitable forB.Tech/Diploma IoT/ESP32 students
- Build time1-2 weeks
- LevelBeginner
- Available atAjvika Labs, Kakinada
About this project
This guide shows how to use the HC-SR04 Ultrasonic Sensor with the ESP32 board using the Arduino core. The ultrasonic sensor uses sonar to determine the distance to an object. We’ll show you how to wire the sensor to the ESP32 and provide several example sketches to determine the distance to an object using the HC-SR04.
This tutorial covers the following topics:
Ultrasonic Sensor HC-SR04 Pinout
Wiring the Ultrasonic Sensor HC-SR04 to the ESP32
Getting Distance to an Object Using the Ultrasonic Sensor HC-SR04 with the ESP32
Displaying the Distance to an Object on a Display Using the ESP32 and HC-SR04
Introducing the HC-SR04 Ultrasonic Sensor
The HC-SR04 ultrasonic sensor uses sonar to determine the distance to an object. This sensor reads from 2cm to 400cm (0.8inch to 157inch) with an accuracy of 0.3cm (0.1inches), which is good for most hobbyist projects. In addition, this particular module comes with ultrasonic transmitter and receiver modules.
The following picture shows the HC-SR04 ultrasonic sensor.
The next picture shows the other side of the sensor.
Where to buy HC-SR04 Ultrasonic Sensor?
You can check the Ultrasonic Sensor HC-SR04 sensor on Maker Advisor to find the best price:
HC-SR04 Ultrasonic Sensor
HC-SR04 Ultrasonic Sensor Technical Data
The following table shows the key features and specs of the HC-SR04 ultrasonic sensor. For more information, you should consult the sensor’s datasheet.
Power Supply
5V DC
Working Current
15 mA
Working Frequency
40 kHz
Maximum Range
4 meters
Minimum Range
2 cm
Measuring Angle
15º
Resolution
0.3 cm
Trigger Input Signal
10uS TTL pulse
Echo Output Signal
TTL pulse proportional to the distance range
Dimensions
45mm x 20mm x 15mm
HC-SR04 Ultrasonic Sensor Pinout
Here’s the pinout of the HC-SR04 Ultrasonic Sensor.
VCC
Powers the sensor (5V)
Trig
Trigger Input Pin
Echo
Echo Output Pin
GND
Common GND
How Does the HC-SR04 Ultrasonic Sensor Work?
The ultrasonic sensor uses sonar to determine the distance to an object. Here’s how it works:
The ultrasound transmitter (trig pin) emits a high-frequency sound (40 kHz).
The sound travels through the air. If it finds an object, it bounces back to the module.
The ultrasound receiver (echo pin) receives the reflected sound (echo).
Taking into account the sound’s velocity in the air and the travel time (time passed since the transmission and reception of the signal) we can calculate the distance to an object. Here’s the formula:
distance to an object = ((speed of sound in the air)*time)/2
speed of sound in the air at 20ºC (68ºF) =
343m/s
Parts Required
To complete this tutorial you need the following parts:
HC-SR04 Ultrasonic Sensor
ESP32
(read
Best ESP32 development boards
)
Breadboard
Jumper wires
You can use the preceding links or go directly to
MakerAdvisor.com/tools
to find all the parts for your projects at the best price!
Schematic – ESP32 with HC-SR04 Ultrasonic Sensor
Wire the HC-SR04 ultrasonic sensor to the ESP32 as shown in the following schematic diagram. We’re connecting the Trig pin to
GPIO 5
and the Echo pin to
GPIO 18
, but you can use any other suitable pins.
Ultrasonic Sensor
ESP32
VCC
VIN
Trig
GPIO 5
Echo
GPIO 18
GND
GND
Preparing Arduino IDE
We’ll program the ESP32 board using Arduino IDE. So, make sure you have the ESP32 add-on installed. Follow the next tutorial:
Install the ESP32 Board in Arduino IDE
If you want to use VS Code with the PlatformIO extension, follow the next tutorial instead to learn how to program the ESP32:
Getting Started with VS Code and PlatformIO IDE for ESP32 and ESP8266 (Windows, Mac OS X, Linux Ubuntu)
Code – Getting Distance to an Object using the HC-SR04 Ultrasonic Sensor and ESP32
The following sketch is a simple example of how you can get the distance between the sensor and an object using the ESP32 board with the Arduino core.
/*********
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*********/
const int trigPin = 5;
const int echoPin = 18;
//define sound speed in cm/uS
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701
long duration;
float distanceCm;
float distanceInch;
void setup() {
Serial.begin(115200); // Starts the serial communication
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distanceCm = duration * SOUND_SPEED/2;
// Convert to inches
distanceInch = distanceCm * CM_TO_INCH;
// Prints the distance in the Serial Monitor
Serial.print(\"Distance (cm): \");
Serial.println(distanceCm);
Serial.print(\"Distance (inch): \");
Serial.println(distanceInch);
delay(1000);
}
Upload the code to your board and it will work straight away. Continue reading if you want to learn how the code works or skip to the
demonstration section
How the Code Works
First, define the trigger and the echo pins.
const int trigPin = 5;
const int echoPin = 18;
In this example, we’re using
GPIO 5
and
GPIO 18
. But you can use any other suitable GPIOs—read
ESP32 Pinout Reference: Which GPIO pins should you use?
The
SOUND_SPEED
variable saves the velocity of sound in the air at 20ºC. We’re using the value in cm/uS.
#define SOUND_SPEED 0.034
The
CM_TO_INCH
variable allows us to convert distance in centimeters to inches.
#define CM_TO_INCH 0.393701
Then, initialize the following variables.
long duration;
float distanceCm;
float distanceInch;
The
duration
variable saves the travel time of the ultrasonic waves (time elapsed since transmission and reception of the pulse wave). The
distanceCm
and
distanceInch
, as the names suggest, save the distance to an object in centimeters and inches.
setup()
In the
setup()
, initialize a serial communication at a baud rate of 115200 so that we can print the measurements on the Serial Monitor.
Serial.begin(115200); // Starts the serial communication
Define the trigger pin as an
OUTPUT
—the trigger pin emits the ultrasound. And define the echo pin as an
INPUT
—the echo pin receives the reflected wave and sends a signal to the ESP32 that is proportional to the travel time.
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
loop()
In the
loop()
, the following lines produce a 10uS
HIGH
pulse on the trigger pin—this means the pin will emit an ultrasound. Note that before sending the pulse, we give a short
LOW
pulse to ensure you’ll get a clean
HIGH
pulse.
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
We use the
pulseIn()
function to get the sound wave travel time:
duration = pulseIn(echoPin, HIGH);
The
pulseIn()
function reads a HIGH or a LOW pulse on a pin. It accepts as arguments the pin and the state of the pulse (either HIGH or LOW). It returns the length of the pulse in microseconds. The pulse length corresponds to the time it took to travel to the object plus the time traveled on the way back.
Then, we simply calculate the distance to an object taking into account the sound speed.
distanceCm = duration * SOUND_SPEED/2;
Convert the distance to inches:
distanceInch = distanceCm * CM_TO_INCH;
And finally, print the result
This tutorial covers the following topics:
Ultrasonic Sensor HC-SR04 Pinout
Wiring the Ultrasonic Sensor HC-SR04 to the ESP32
Getting Distance to an Object Using the Ultrasonic Sensor HC-SR04 with the ESP32
Displaying the Distance to an Object on a Display Using the ESP32 and HC-SR04
Introducing the HC-SR04 Ultrasonic Sensor
The HC-SR04 ultrasonic sensor uses sonar to determine the distance to an object. This sensor reads from 2cm to 400cm (0.8inch to 157inch) with an accuracy of 0.3cm (0.1inches), which is good for most hobbyist projects. In addition, this particular module comes with ultrasonic transmitter and receiver modules.
The following picture shows the HC-SR04 ultrasonic sensor.
The next picture shows the other side of the sensor.
Where to buy HC-SR04 Ultrasonic Sensor?
You can check the Ultrasonic Sensor HC-SR04 sensor on Maker Advisor to find the best price:
HC-SR04 Ultrasonic Sensor
HC-SR04 Ultrasonic Sensor Technical Data
The following table shows the key features and specs of the HC-SR04 ultrasonic sensor. For more information, you should consult the sensor’s datasheet.
Power Supply
5V DC
Working Current
15 mA
Working Frequency
40 kHz
Maximum Range
4 meters
Minimum Range
2 cm
Measuring Angle
15º
Resolution
0.3 cm
Trigger Input Signal
10uS TTL pulse
Echo Output Signal
TTL pulse proportional to the distance range
Dimensions
45mm x 20mm x 15mm
HC-SR04 Ultrasonic Sensor Pinout
Here’s the pinout of the HC-SR04 Ultrasonic Sensor.
VCC
Powers the sensor (5V)
Trig
Trigger Input Pin
Echo
Echo Output Pin
GND
Common GND
How Does the HC-SR04 Ultrasonic Sensor Work?
The ultrasonic sensor uses sonar to determine the distance to an object. Here’s how it works:
The ultrasound transmitter (trig pin) emits a high-frequency sound (40 kHz).
The sound travels through the air. If it finds an object, it bounces back to the module.
The ultrasound receiver (echo pin) receives the reflected sound (echo).
Taking into account the sound’s velocity in the air and the travel time (time passed since the transmission and reception of the signal) we can calculate the distance to an object. Here’s the formula:
distance to an object = ((speed of sound in the air)*time)/2
speed of sound in the air at 20ºC (68ºF) =
343m/s
Parts Required
To complete this tutorial you need the following parts:
HC-SR04 Ultrasonic Sensor
ESP32
(read
Best ESP32 development boards
)
Breadboard
Jumper wires
You can use the preceding links or go directly to
MakerAdvisor.com/tools
to find all the parts for your projects at the best price!
Schematic – ESP32 with HC-SR04 Ultrasonic Sensor
Wire the HC-SR04 ultrasonic sensor to the ESP32 as shown in the following schematic diagram. We’re connecting the Trig pin to
GPIO 5
and the Echo pin to
GPIO 18
, but you can use any other suitable pins.
Ultrasonic Sensor
ESP32
VCC
VIN
Trig
GPIO 5
Echo
GPIO 18
GND
GND
Preparing Arduino IDE
We’ll program the ESP32 board using Arduino IDE. So, make sure you have the ESP32 add-on installed. Follow the next tutorial:
Install the ESP32 Board in Arduino IDE
If you want to use VS Code with the PlatformIO extension, follow the next tutorial instead to learn how to program the ESP32:
Getting Started with VS Code and PlatformIO IDE for ESP32 and ESP8266 (Windows, Mac OS X, Linux Ubuntu)
Code – Getting Distance to an Object using the HC-SR04 Ultrasonic Sensor and ESP32
The following sketch is a simple example of how you can get the distance between the sensor and an object using the ESP32 board with the Arduino core.
/*********
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*********/
const int trigPin = 5;
const int echoPin = 18;
//define sound speed in cm/uS
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701
long duration;
float distanceCm;
float distanceInch;
void setup() {
Serial.begin(115200); // Starts the serial communication
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distanceCm = duration * SOUND_SPEED/2;
// Convert to inches
distanceInch = distanceCm * CM_TO_INCH;
// Prints the distance in the Serial Monitor
Serial.print(\"Distance (cm): \");
Serial.println(distanceCm);
Serial.print(\"Distance (inch): \");
Serial.println(distanceInch);
delay(1000);
}
Upload the code to your board and it will work straight away. Continue reading if you want to learn how the code works or skip to the
demonstration section
How the Code Works
First, define the trigger and the echo pins.
const int trigPin = 5;
const int echoPin = 18;
In this example, we’re using
GPIO 5
and
GPIO 18
. But you can use any other suitable GPIOs—read
ESP32 Pinout Reference: Which GPIO pins should you use?
The
SOUND_SPEED
variable saves the velocity of sound in the air at 20ºC. We’re using the value in cm/uS.
#define SOUND_SPEED 0.034
The
CM_TO_INCH
variable allows us to convert distance in centimeters to inches.
#define CM_TO_INCH 0.393701
Then, initialize the following variables.
long duration;
float distanceCm;
float distanceInch;
The
duration
variable saves the travel time of the ultrasonic waves (time elapsed since transmission and reception of the pulse wave). The
distanceCm
and
distanceInch
, as the names suggest, save the distance to an object in centimeters and inches.
setup()
In the
setup()
, initialize a serial communication at a baud rate of 115200 so that we can print the measurements on the Serial Monitor.
Serial.begin(115200); // Starts the serial communication
Define the trigger pin as an
OUTPUT
—the trigger pin emits the ultrasound. And define the echo pin as an
INPUT
—the echo pin receives the reflected wave and sends a signal to the ESP32 that is proportional to the travel time.
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
loop()
In the
loop()
, the following lines produce a 10uS
HIGH
pulse on the trigger pin—this means the pin will emit an ultrasound. Note that before sending the pulse, we give a short
LOW
pulse to ensure you’ll get a clean
HIGH
pulse.
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
We use the
pulseIn()
function to get the sound wave travel time:
duration = pulseIn(echoPin, HIGH);
The
pulseIn()
function reads a HIGH or a LOW pulse on a pin. It accepts as arguments the pin and the state of the pulse (either HIGH or LOW). It returns the length of the pulse in microseconds. The pulse length corresponds to the time it took to travel to the object plus the time traveled on the way back.
Then, we simply calculate the distance to an object taking into account the sound speed.
distanceCm = duration * SOUND_SPEED/2;
Convert the distance to inches:
distanceInch = distanceCm * CM_TO_INCH;
And finally, print the result
Technologies used
Hardware components
- ESP32
- ESP8266
- Arduino
- HC-SR04
Software & tools
- Arduino IDE
- VS Code
- PlatformIO
- PlatformIO
What you get
- Working project / hardware kit, tested before delivery
- Complete source code with explanation
- Project demo and guidance for your viva
- Project report, PPT and IEEE paper support (on request)
Delivery & Payment
Delivery takes a minimum of two weeks from the date your inquiry is confirmed.
Payment is in two parts:
• 50% advance to start the project
• Remaining 50% before delivery
Note:
• Documentation and PPT are not included by default
• If you need documentation/PPT, it can be arranged for extra time and cost
We'll confirm the exact timeline and cost with you after reviewing your requirements.