#define echoPin 34 // attach pin ESP32 GPIO34 to pin Echo of HC-SR04
#define trigPin 25 // attach pin ESP32 GPIO25 to pin Trig of HC-SR04
#define relayIn 23
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
pinMode(relayIn, OUTPUT);
Serial.println("Distance measurement using ESP32");
delay(500);
//Serial.println("Hello, ESP32!");
}
void loop() {
// put your main code here, to run repeatedly:
long d=distance();
Serial.println("Distance:"+String(d));
if(d>200) digitalWrite(relayIn, HIGH);
else digitalWrite(relayIn, LOW);
delay(1000); // this speeds up the simulation
}
long distance()
{
long duration;
digitalWrite(trigPin, LOW);
delayMicroseconds(2); // wait for 2 ms to avoid
// collision in the 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
// If pulse reached the receiver echoPin
// become high Then pulseIn() returns the
// time taken by the pulse to reach the
// receiver
duration = pulseIn(echoPin, HIGH);
return duration * 0.0344 / 2; // Expression to calculate
// distance using time
}