#include <Servo.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// IR sensor pins
const int irPinIn = 2;
const int irPinOut = 3;
// Servo motor pin
const int servoPin = 6;
// Parking space variables
int currentCount = 0;
const int maxSpaces = 4; // Tunable max parking spaces
Servo gateServo;
LiquidCrystal_I2C lcd(0x27, 16, 2); // Common I2C address: 0x27 or 0x3F
// Function to open gate
void openGate() {
/*
IO: servoPin (output to servo)
Working: Rotates servo to 90° (gate open)
*/
gateServo.write(90);
}
// Function to close gate
void closeGate() {
/*
IO: servoPin (output to servo)
Working: Rotates servo back to 0° (gate closed)
*/
gateServo.write(0);
}
// Function to update LCD
void updateLcd(const char* line1, const char* line2) {
/*
IO: LCD I2C (16x2)
Working: Clears screen and writes 2 lines of text
*/
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(line1);
lcd.setCursor(0, 1);
lcd.print(line2);
}
void setup() {
Serial.begin(9600);
pinMode(irPinIn, INPUT);
pinMode(irPinOut, INPUT);
gateServo.attach(servoPin);
closeGate();
lcd.init();
lcd.backlight();
updateLcd("Smart Parking", "System Ready");
delay(2000);
updateLcd("Car Count:", "0");
}
void loop() {
int carIn = digitalRead(irPinIn);
int carOut = digitalRead(irPinOut);
Serial.print("irIn: ");Serial.print(carIn);Serial.print(" | irOUT: ");Serial.println(carOut);
// lcd.clear();
lcd.setCursor(0, 0);lcd.print("Smart Parking Sys");
lcd.setCursor(0, 1);lcd.print("Car : ");lcd.print(currentCount);lcd.print("/");lcd.print(maxSpaces);
// Car entering
if (carIn == HIGH) { // IR sensor detects object when LOW
if (currentCount < maxSpaces) {
openGate();
updateLcd("Welcome!", "Gate Opening...");
delay(3000); // Allow car to pass
closeGate();
currentCount++;
char buffer[16];
sprintf(buffer, "Car Count: %d", currentCount);
updateLcd("Entry Success", buffer);
Serial.print("Car Entered. Current Count: ");
Serial.println(currentCount);
delay(2000); // Debounce delay
lcd.clear();
} else {
updateLcd("Parking Full!", "Access Denied");
Serial.println("Parking Full! Gate not opened.");
delay(2000);
lcd.clear();
}
}
// Car exiting
if (carOut == HIGH) { // IR detects car leaving
openGate();
updateLcd("Goodbye!", "Drive Safely");
delay(3000);
closeGate();
if (currentCount > 0) {
currentCount--;
}
char buffer[16];
sprintf(buffer, "Car Count: %d", currentCount);
updateLcd("Exit Success", buffer);
Serial.print("Car Exited. Current Count: ");
Serial.println(currentCount);
delay(2000); // Debounce delay
lcd.clear();
}
delay(200); // Small loop delay
// delay(10); // Small loop delay
}