#include <Servo.h>
// Pin definitions for ultrasonic sensor
const int trigPin = 5; // Pin trig untuk sensor ultrasonik
const int echoPin = 18; // Pin echo untuk sensor ultrasonik
// Pin definition for servo motor
const int servoPin = 13;
Servo servoMotor;
// Threshold distance to open gate (in cm)
const int openDistance = 10;
// Variables for ultrasonic sensor
long duration;
int distance;
void setup() {
// Initialize the serial communication for debugging
Serial.begin(115200);
// Set trigPin as output and echoPin as input
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Attach servo motor to the specified pin
servoMotor.attach(servoPin);
// Start with the gate closed (set servo to 0 degrees)
servoMotor.write(0);
}
void loop() {
// Send a 10us pulse to trigger the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo pin and calculate the distance
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2; // Convert to cm
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// If distance is less than or equal to threshold, open the gate
if (distance <= openDistance) {
Serial.println("Vehicle detected! Opening gate...");
servoMotor.write(90); // Open the gate (90 degrees)
} else {
Serial.println("No vehicle detected. Closing gate...");
servoMotor.write(0); // Close the gate (0 degrees)
}
// Wait for 500ms before the next reading
delay(500);
}