#include <Servo.h>
const int trigPin = 2; // Ultrasonic sensor trigger pin
const int echoPin = 3; // Ultrasonic sensor echo pin
const int servoPin = 4; // Servo motor signal pin
Servo gateServo; // Create a servo object
long duration;
int distance;
void setup() {
gateServo.attach(servoPin); // Attach servo to its pin
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// Ultrasonic sensor operation
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
// Control the gate based on distance
if (distance < 10) { // Adjust the distance value as needed
openGate(); // If an object is close, open the gate
} else {
closeGate(); // Otherwise, close the gate
}
delay(500); // Adjust the delay as needed for your setup
}
void openGate() {
gateServo.write(90); // Open position (90 degrees)
delay(1000); // Adjust the delay as needed to allow time for the gate
}
void closeGate() {
gateServo.write(0); // close position (0 degrees)
delay(1000); // Adjust the delay as needed to allow time for the gate
}