
How to Use HC-SR04 Ultrasonic Sensor with ESP32
Welcome to our guide on using the HC-SR04 ultrasonic sensor with the ESP32 microcontroller. In this article, we will walk you through the process of setting up and programming the HC-SR04 sensor to work with the ESP32 development board.
The HC-SR04 ultrasonic sensor is a popular choice for distance measurement in robotics and IoT projects. It uses ultrasonic waves to determine the distance between the sensor and an object. When combined with the ESP32, you can create powerful projects that require accurate distance measurements.
Components Required
- ESP32 Development Board
- HC-SR04 Ultrasonic Sensor
- Jumper Wires
- Breadboard
- USB Cable
Wiring the HC-SR04 Sensor with ESP32
Start by connecting the HC-SR04 ultrasonic sensor to the ESP32 development board using jumper wires. Make sure to connect the VCC pin of the sensor to the 5V pin of the ESP32, the Trig pin to GPIO pin 2, the Echo pin to GPIO pin 4, and the GND pin to the GND pin of the ESP32.

Programming the ESP32
Next, you’ll need to write the code to program the ESP32 to read data from the HC-SR04 sensor. You can use the Arduino IDE, which has support for the ESP32 board. Make sure to include the “Ultrasonic.h” library in your sketch to interface with the HC-SR04 sensor.
Here is a sample code snippet to get you started:
#include <Ultrasonic.h>
#define trigPin 2
#define echoPin 4
Ultrasonic ultrasonic(trigPin, echoPin);
void setup() {
Serial.begin(9600);
}
void loop() {
int distance = ultrasonic.Ranging(CM);
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(1000);
}
Upload the code to your ESP32 board and open the serial monitor to view the distance measurements in centimeters. You can further enhance the code to incorporate the sensor data into your project.
Conclusion
Using the HC-SR04 ultrasonic sensor with the ESP32 opens up a world of possibilities for your projects. Whether you’re building a robot, a smart home device, or a monitoring system, the combination of these two components provides accurate and reliable distance measurements. Experiment with different scenarios and have fun creating innovative solutions!
Was this helpful?
0 / 0