ESP32 - Ultrasonic Sensor
This tutorial instructs you how to use ESP32 with the ultrasonic sensor HC-SR04 to measure the distance to an object.
Hardware Used In This Tutorial
1 | × | ESP-WROOM-32 Dev Module | |
1 | × | USB Cable Type-C | |
1 | × | Ultrasonic Sensor | |
1 | × | Breadboard | |
1 | × | Jumper Wires | |
1 | × | (Optional) DC Power Jack | |
1 | × | (Recommended) ESP32 Screw Terminal Adapter |
Or you can buy the following sensor kit:
1 | × | DIYables Sensor Kit 30 types, 69 units |
Introduction to Ultrasonic Sensor
The ultrasonic sensor HC-SR04 is used to measure the distance from the sensor to an object by using ultrasonic waves.
Ultrasonic Sensor Pinout
The ultrasonic sensor HC-SR04 includes four pins:
- VCC pin: connect this pin to VCC (5V)
- GND pin: connect this pin to GND (0V)
- TRIG pin: this pin receives a control pulse from ESP32.
- ECHO pin: this pin generates a pulse corresponding to the measured distance to ESP32.

How Ultrasonic Sensor Works
Wiring Diagram between Ultrasonic Sensor and ESP32
The wiring diagram with power supply from USB cable

This image is created using Fritzing. Click to enlarge image
If you're unfamiliar with how to supply power to the ESP32 and other components, you can find guidance in the following tutorial: How to Power ESP32.
The wiring diagram with power supply from 5v adapter

This image is created using Fritzing. Click to enlarge image
How To Program Ultrasonic Sensor
- Generate a 10-microsecond pulse in ESP32's pin by using digitalWrite() and delayMicroseconds() functions. For example, pin GPIO23:
- Measures the pulse duration (µs) in ESP32's pin by using pulseIn() function. For example, pin GPIO22:
- Calculate distance (cm):
ESP32 Code
Quick Instructions
- If this is the first time you use ESP32, see how to setup environment for ESP32 on Arduino IDE.
- Copy the above code and paste it to Arduino IDE.
- Compile and upload code to ESP32 board by clicking Upload button on Arduino IDE

- Open Serial Monitor on Arduino IDE

- Move your hand in front of ultrasonic sensor
- See the distance from the sensor to your hand on Serial Monitor
Line-by-line Code Explanation
The above ESP32 code contains line-by-line explanation. Please read the comments in the code!
How to Filter Noise from Distance Measurements of Ultrasonic Sensor
See How to Filter Noise from Distance Measurements of Ultrasonic Sensor
Video Tutorial
Making video is a time-consuming work. If the video tutorial is necessary for your learning, please let us know by subscribing to our YouTube channel , If the demand for video is high, we will make the video tutorial.