#include <Servo.h>
const int trigPin = 6;
const int echoPin = 7;
Servo myServo;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
myServo.attach(9);
myServo.write(0); // Gate closed position
}
void loop() {
long duration, distance;
// Send ultrasonic pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read echo time
duration = pulseIn(echoPin, HIGH);
// Calculate distance in cm
distance = duration * 0.034 / 2;
if (distance < 20) { // If object is within 20 cm
myServo.write(120); // Open gate
delay(3000); // Keep gate open for 3 seconds
myServo.write(0); // Close gate
}
delay(500); // Wait before next measurement
}
No comments:
Post a Comment