#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
// إعداد دبابيس حساس الدخول (Ultrasonic 1)
const int TRIG_ENTRANCE = 2;
const int ECHO_ENTRANCE = 3;
// إعداد دبابيس حساس الخروج (Ultrasonic 2)
const int TRIG_EXIT = 5;
const int ECHO_EXIT = 6;
// دبوس محرك السيرفو
const int SERVO_PIN = 4;
// إعدادات الموقف
const int MAX_SPACES = 5;
int current_cars = 0;
LiquidCrystal_I2C lcd(0x27, 16, 2);
Servo gateServo;
// دالة لحساب المسافة بالسنتيمتر
long readDistance(int trigPin, int echoPin) {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
return duration * 0.034 / 2;
}
void updateDisplay() {
int free_spaces = MAX_SPACES - current_cars;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Total Slots: ");
lcd.print(MAX_SPACES);
lcd.setCursor(0, 1);
lcd.print("Available: ");
lcd.print(free_spaces);
}
void openGate() {
gateServo.write(90); // فتح البوابة
delay(3000); // وقت عبور السيارة
gateServo.write(0); // إغلاق البوابة
}
void setup() {
Serial.begin(115200);
pinMode(TRIG_ENTRANCE, OUTPUT);
pinMode(ECHO_ENTRANCE, INPUT);
pinMode(TRIG_EXIT, OUTPUT);
pinMode(ECHO_EXIT, INPUT);
gateServo.attach(SERVO_PIN);
gateServo.write(0);
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print(" Smart Parking ");
lcd.setCursor(0, 1);
lcd.print(" Nucleo C031C6 ");
delay(2000);
updateDisplay();
}
void loop() {
long distanceEntrance = readDistance(TRIG_ENTRANCE, ECHO_ENTRANCE);
long distanceExit = readDistance(TRIG_EXIT, ECHO_EXIT);
// كشف سيارة عند مدخل الموقف (المسافة أقل من 20 سم تعني وجود سيارة)
if (distanceEntrance > 0 && distanceEntrance < 20) {
if (current_cars < MAX_SPACES) {
current_cars++;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Car Entering...");
openGate();
updateDisplay();
} else {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(" Parking FULL! ");
delay(2000);
updateDisplay();
}
delay(1000); // منع التكرار الفوري لقراءة نفس السيارة
}
// كشف سيارة عند مخرج الموقف
if (distanceExit > 0 && distanceExit < 20) {
if (current_cars > 0) {
current_cars--;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Car Leaving... ");
openGate();
updateDisplay();
}
delay(1000);
}
delay(100);
}