#include <Arduino.h> // Required for ESP32
#include <ESP32Servo.h> // ESP32-specific servo library
#include <LiquidCrystal_I2C.h>// I2C LCD library
// --- PIN DEFINITIONS ---
#define IR_GATE_PIN 27 // IR sensor for vehicle detection
#define IR_SPOT1_PIN 14 // IR sensor for Spot 1
#define IR_SPOT2_PIN 15 // IR sensor for Spot 2
#define SERVO_PIN 2 // Servo motor for gate control
#define RED_LED_PIN 26 // Red LED (gate closed/error)
#define GREEN_LED_PIN 25 // Green LED (gate open/success)
// Initialize LCD (address 0x27 for common I2C LCDs)
LiquidCrystal_I2C lcd(0x27, 16, 2);
Servo gate; // ESP32-compatible servo object
void setup() {
Serial.begin(115200);
// Initialize pins
pinMode(IR_GATE_PIN, INPUT);
pinMode(IR_SPOT1_PIN, INPUT);
pinMode(IR_SPOT2_PIN, INPUT);
pinMode(RED_LED_PIN, OUTPUT);
pinMode(GREEN_LED_PIN, OUTPUT);
// Attach servo with ESP32-specific PWM settings
gate.setPeriodHertz(50); // Standard 50Hz PWM frequency
gate.attach(SERVO_PIN, 500, 2400); // Min 500µs, max 2400µs pulse
// Initialize LCD
lcd.init();
lcd.backlight();
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Smart Parking");
lcd.setCursor(0, 1);
lcd.print("Demo Mode");
delay(2000);
lcd.clear();
// Start with gate closed and red LED on
gate.write(0);
digitalWrite(RED_LED_PIN, HIGH);
digitalWrite(GREEN_LED_PIN, LOW);
}
void loop() {
// Check for vehicle approach (gate trigger)
if (digitalRead(IR_GATE_PIN) == LOW) { // Vehicle detected
openGate();
}
// Read IR sensors for spot availability
bool spot1Available = (digitalRead(IR_SPOT1_PIN) == HIGH); // HIGH = no car (available)
bool spot2Available = (digitalRead(IR_SPOT2_PIN) == HIGH); // HIGH = no car (available)
// Update LCD with spot status
updateLCD(spot1Available, spot2Available);
delay(500); // Update LCD every 500ms
}
// Open the gate when a vehicle approaches
void openGate() {
digitalWrite(RED_LED_PIN, LOW); // Turn off red LED
digitalWrite(GREEN_LED_PIN, HIGH); // Turn on green LED
gate.write(90); // Rotate servo to 90° (open gate)
delay(2000); // Keep gate open for 2 seconds
gate.write(0); // Close gate
digitalWrite(GREEN_LED_PIN, LOW); // Turn off green LED
digitalWrite(RED_LED_PIN, HIGH); // Turn on red LED
}
// Update LCD with spot availability
void updateLCD(bool spot1Avail, bool spot2Avail) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Spot 1: ");
lcd.print(spot1Avail ? "Available" : "Full");
lcd.setCursor(0, 1);
lcd.print("Spot 2: ");
lcd.print(spot2Avail ? "Available" : "Full");
}