#include <Servo.h>
int duration1, distance1; // Variables for sensor 1 (entry)
int duration2, distance2; // Variables for sensor 2 (exit)
// initialize servo motor with name "gate"
Servo gate;
void setup() {
pinMode(9, OUTPUT);
pinMode(8, INPUT);
pinMode(12, OUTPUT);
pinMode(11, INPUT);
pinMode(2, OUTPUT);
pinMode(4, OUTPUT);
gate.attach(3); // connect servo to pin 3 (PWM)
// Initially close the gate
gate.write(0); // gate is closed angle = 0
digitalWrite(2, HIGH); // Red LED on (gate closed)
digitalWrite(4, LOW); // Green LED off
}
void loop() {
// Measure distance from sensor 1 (entry detection)
digitalWrite(9, LOW); // control trigger pin to activate sensor
delayMicroseconds(2);
digitalWrite(9, HIGH);
delayMicroseconds(10);
digitalWrite(9, LOW); // control trigger pin to activate sensor
duration1 = pulseIn(8, HIGH); // read time value from echo pin
distance1 = duration1 * 0.034 / 2; // Convert to cm
// Vehicle detected at entry (distance less than 10 cm)
if (distance1 < 10) {
// Open the gate
gate.write(90);
delay(1000); // Time to fully open the gate ( check and change based on your physical system)
// Turn off red LED, turn on green LED (gate open)
digitalWrite(2, LOW);
digitalWrite(4, HIGH);
// Read ultrasonic sensor on the exit
digitalWrite(12, LOW);
delayMicroseconds(2);
digitalWrite(12, HIGH);
delayMicroseconds(10);
digitalWrite(12, LOW);
duration2 = pulseIn(11, HIGH);
distance2 = duration2 * 0.034 / 2; // Convert to cm
while (distance2 > 10 || distance1 < 10) {
// Check sensor 2 (exit detection)
digitalWrite(12, LOW);
delayMicroseconds(2);
digitalWrite(12, HIGH);
delayMicroseconds(10);
digitalWrite(12, LOW);
duration2 = pulseIn(11, HIGH);
distance2 = duration2 * 0.034 / 2; // Convert to cm
// Check sensor 1 (entry detection) again in case another vehicle arrives
digitalWrite(9, LOW);
delayMicroseconds(2);
digitalWrite(9, HIGH);
delayMicroseconds(10);
digitalWrite(9, LOW);
duration1 = pulseIn(8, HIGH);
distance1 = duration1 * 0.034 / 2; // Convert to cm
}
// Close the gate after the vehicle has passed
gate.write(0);
delay(1000); // Time to fully close the gate
// Turn on red LED, turn off green LED (gate closed)
digitalWrite(2, HIGH);
digitalWrite(4, LOW);
}
// Small delay to avoid excessive sensor triggering
delay(200);
}