#define trigPin 2 // attach pin D2 Arduino to pin Echo of HC-SR04
#define echoPin 3 // attach pin D3 Arduino to pin Trig of HC-SR04
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT); //Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
// Serial Communication is starting with 9600 of
// baudrate speed
Serial.begin(9600);
// The text to be printed in serial monitor
Serial.println("Distance measurement using ESP32.");
delay(500);
}
void loop() {
// Send a 10µs pulse to trigger the sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);// wait for 2 ms to avoid
// collision in serial monitor
digitalWrite(trigPin, HIGH);// turn on the Trigger to generate pulse
delayMicroseconds(10);// keep the trigger "ON" for 10 ms to generate
// pulse for 10 ms.
digitalWrite(trigPin, LOW);// Turn off the pulse trigger to stop
// pulse generation
// Measure the time of the echo pulse
duration = pulseIn(echoPin, HIGH);
// Convert duration to distance (in cm)
distance = duration * 0.0344 / 2; // Expression to calculate
// distance using time
// Display the distance
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(5000); //the process repeats every 5 seconds.
}