Overview
Learn how to use the HC-SR04 ultrasonic sensor with an ESP32 to measure distance in centimeters. This project is useful for obstacle detection, smart parking, and simple distance alarms.
Instructions
Step by step
1. Connect the HC-SR04 VCC pin to 5V.
2. Connect the HC-SR04 GND pin to GND.
3. Connect the Trig pin to D5.
4. Connect the Echo pin to D18.
5. Run the code and open the Serial Monitor.
6. Change the object distance in the simulator.
7. Check if the printed distance changes in centimeters.
Code
Source code
const int trigPin = 5;
const int echoPin = 18;
void setup() {
Serial.begin(115200);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.println("HC-SR04 Distance Test");
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
float distance = (duration * 0.0343) / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(1000);
}