#include <Servo.h>
#define TRIGGER_PIN_1 9 // Trigger pin for Ultrasonic Sensor 1
#define ECHO_PIN_1 8 // Echo pin for Ultrasonic Sensor 1
#define TRIGGER_PIN_2 4 // Trigger pin for Ultrasonic Sensor 2
#define ECHO_PIN_2 5 // Echo pin for Ultrasonic Sensor 2
#define SERVO_PIN 7 // Servo motor control pin
Servo gateServo;
long duration_1, duration_2;
int distance_1, distance_2;
void setup() {
pinMode(TRIGGER_PIN_1, OUTPUT);
pinMode(ECHO_PIN_1, INPUT);
pinMode(TRIGGER_PIN_2, OUTPUT);
pinMode(ECHO_PIN_2, INPUT);
gateServo.attach(SERVO_PIN);
gateServo.write(90); // Initialize servo position to 90 degrees (closed gate)
Serial.begin(9600);
}
void loop() {
// Measure distance from Ultrasonic Sensor 1
digitalWrite(TRIGGER_PIN_1, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN_1, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN_1, LOW);
duration_1 = pulseIn(ECHO_PIN_1, HIGH);
distance_1 = duration_1 * 0.034 / 2; // Calculate distance in cm
// Measure distance from Ultrasonic Sensor 2
digitalWrite(TRIGGER_PIN_2, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN_2, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN_2, LOW);
duration_2 = pulseIn(ECHO_PIN_2, HIGH);
distance_2 = duration_2 * 0.034 / 2; // Calculate distance in cm
// Check if a train is detected by either sensor
if (distance_1 < 4|| distance_2 < 4) { // Adjust the threshold distance as needed
closeGate();
delay(4000); // Wait for 5 seconds (gate closed)
openGate();
}
}
void closeGate() {
gateServo.write(0); // Close the gate (adjust the angle as needed)
}
void openGate() {
gateServo.write(90); // Open the gate (adjust the angle as needed)
}