Arduino Nano ESP32 - Ultrasonic Sensor
This tutorial provides instructions on how to use Arduino Nano ESP32 with the ultrasonic sensor HC-SR04 to measure the distance to an object.
Hardware Preparation
Or you can buy the following kits:
| 1 | × | DIYables Sensor Kit (18 sensors/displays) |
Additionally, some of these links are for products from our own brand, DIYables .
Overview of 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 Arduino Nano ESP32.
- ECHO pin: this pin generates a pulse corresponding to the measured distance to Arduino Nano ESP32.

How Ultrasonic Sensor Works
Wiring Diagram between Ultrasonic Sensor and Arduino Nano ESP32
- The wiring diagram when powering the Arduino Nano ESP32 board via USB port.

This image is created using Fritzing. Click to enlarge image
If you do not use a breadboard, wire it like this:

This image is created using Fritzing. Click to enlarge image
Pushing jumper wires into the headers is quick, but the wires can slip out. Put the Arduino Nano ESP32 on a Screw Terminal Expansion Board for Arduino Nano, then tighten each wire under a screw. The wiring stays the same. Only the wires now go to the screw terminals, as shown below.

This image is created using Fritzing. Click to enlarge image
- The wiring diagram when powering the Arduino Nano ESP32 board via Vin pin.

This image is created using Fritzing. Click to enlarge image
The diagram below shows the same connections without a breadboard:

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 D2:
- Measures the pulse duration (µs) in ESP32's pin by using pulseIn() function. For example, pin D3:
- Calculate distance (cm):
Arduino Nano ESP32 Code
Detailed Instructions
- If this is the first time you use Arduino Nano ESP32, see how to setup environment for Arduino Nano ESP32 on Arduino IDE.
- Copy the above code and paste it to Arduino IDE.
- Compile and upload code to Arduino Nano 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 Arduino Nano 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