ESP32 - Ultrasonic Sensor
by DIYables in Circuits > Microcontrollers
64 Views, 0 Favorites, 0 Comments
ESP32 - Ultrasonic Sensor
This is a compact build guide. The full tutorial, with the wiring diagram and a line-by-line walkthrough of the code, is here: https://esp32io.com/tutorials/esp32-ultrasonic-sensor
This build uses an ESP32 with the HC-SR04 ultrasonic sensor to measure the distance from the sensor to an object. The ESP32 triggers the sensor, times the returning echo pulse, and converts that time into a distance reading printed to the serial monitor.
Supplies
Everything below is what the build uses. The links go to the parts we make and test.
- 38-pin ESP32 ESP-WROOM-32 Dev Module - Narrow
- 38-pin ESP32 ESP-WROOM-32 Dev Module - Wide
- 30-pin ESP32 ESP-WROOM-32 Dev Module - Wide
- ESP32 Uno-form board
- ESP32 S3 Uno-form board
- USB Cable Type-A to Type-C (for USB-A PC)
- USB Cable Type-C to Type-C (for USB-C PC)
- Ultrasonic Sensor
- Breadboard
- Jumper Wires
- DC Power Jack
- Screw Terminal Expansion Board for ESP32
- Breakout Expansion Board for ESP32
- Power Splitter for ESP32
- DIYables ESP32 Starter Kit (ESP32 included)
- DIYables ESP32 S3 Starter Kit (ESP32 S3 included)
- DIYables Sensor Kit (18 sensors/displays)
Wiring
The HC-SR04 has four pins: VCC, GND, TRIG, and ECHO. Connect VCC to the ESP32's 5V, and GND to GND. Connect TRIG to a digital pin such as GPIO23, which sends the control pulse from the ESP32 to the sensor. Connect ECHO to another digital pin such as GPIO22, which carries the return pulse back to the ESP32. You can wire this on a breadboard, or use a screw terminal breakout board, and power the ESP32 either through USB or through the Vin pin.
How It Works
The ESP32 sends a 10-microsecond HIGH pulse on the TRIG pin to fire the sensor. The HC-SR04 then sends out an ultrasonic wave and raises its ECHO pin for the time it takes the wave to bounce off an object and return. The ESP32 measures how long ECHO stays HIGH with pulseIn(), and that duration is used to calculate the distance to the object in centimeters.
Code
The sketch sets the TRIG pin as output and the ECHO pin as input. In the loop, it pulses TRIG HIGH for 10 microseconds using digitalWrite() and delayMicroseconds(), then reads the echo duration on the ECHO pin with pulseIn(). That duration is converted into a distance value and sent to the serial monitor with Serial.println(), repeating with a short delay() between readings.
esp32-ultrasonic-sensor.ino - the sketch from the tutorial, unchanged.
Full Tutorial
The complete tutorial, wiring diagram and code explanation: https://esp32io.com/tutorials/esp32-ultrasonic-sensor