const int trigPin = 4;
const int echoPin = 18;
const int buzzer = 2;
long duration;
int distance;
void setup() {
// put your setup code here, to run once:
pinMode(trigPin, OUTPUT);
pinMode(echoPin, OUTPUT);
pinMode(buzzer,OUTPUT);
pinMode(5, OUTPUT);
Serial.begin(9600);
// Serial.println("Hello, ESP32!");
}
void loop()
{
// put your main code here, to run repeatedly:
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microsec.
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= (duration*0.034)/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println("cm");
delay(500); //500 m.sec = 0.5 sec
tone(buzzer, 1000);
delay(1000);
noTone(buzzer);
delay(1000);
digitalWrite(5, HIGH);
delay(1000);
}