#include <ESP32Servo.h>
#define TRIG_PIN 5
#define ECHO_PIN 18
#define SERVO_PIN 15
Servo gateServo;
long duration;
float distance;
void setup() {
Serial.begin(115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
gateServo.attach(SERVO_PIN);
gateServo.write(0);
}
float readDistance() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
distance = duration * 0.034 / 2;
return distance;
}
void loop() {
float d = readDistance();
Serial.print("Distance: ");
Serial.println(d);
if (d < 20) {
gateServo.write(90);
} else {
gateServo.write(0);
}
delay(500);
}