#include <Servo.h>
#include <NewPing.h> // Including Library for ultrasonic sensor
#define TRIGGER_PIN 4
#define ECHO_PIN 3
#define MAX_DISTANCE 400 // Maximum distance we want to measure (in cm)
#define OPEN_POSITION 0 // Angle for the gate to be open
#define CLOSED_POSITION 90// Angle for the gate to be closed
#define THRESHOLD_DISTANCE 100 // Distance threshold for opening the gate (in cm)
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
Servo gateServo;
void setup() {
gateServo.attach(9); // Attach the servo to pin 9
gateServo.write(CLOSED_POSITION); // Initially keep the gate closed
Serial.begin(9600);
}
void loop() {
delay(50); // Wait for a bit between pings
unsigned int distance = sonar.ping_cm(); // Get distance in cm
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
// Serial.println("cm");
if (distance > 0 && distance < THRESHOLD_DISTANCE) {
// If an object is detected within the threshold distance, open the gate
gateServo.write(OPEN_POSITION);
//Serial.println("Gate Opened");
} else {
// If no object is detected within the threshold distance, close the gate
gateServo.write(CLOSED_POSITION);
//Serial.println("Gate Closed");
}
delay(100); // Small delay to prevent bouncing
}