From 2a853d01042d1e7fe7a7a93098ef3ef7f3f9bdaf Mon Sep 17 00:00:00 2001 From: SOHAM-GADEKAR Date: Thu, 23 Oct 2025 12:10:37 +0530 Subject: [PATCH] Added Smart Door Lock IOT Project --- .../IoT/MiniProjects/SmartDoorLock/README.md | 289 ++++++++++++++++ .../SmartDoorLock/circuit_diagram.md | 198 +++++++++++ .../IoT/MiniProjects/SmartDoorLock/code.ino | 311 ++++++++++++++++++ 3 files changed, 798 insertions(+) create mode 100644 Domains/IoT/MiniProjects/SmartDoorLock/README.md create mode 100644 Domains/IoT/MiniProjects/SmartDoorLock/circuit_diagram.md create mode 100644 Domains/IoT/MiniProjects/SmartDoorLock/code.ino diff --git a/Domains/IoT/MiniProjects/SmartDoorLock/README.md b/Domains/IoT/MiniProjects/SmartDoorLock/README.md new file mode 100644 index 00000000..30bb0ebd --- /dev/null +++ b/Domains/IoT/MiniProjects/SmartDoorLock/README.md @@ -0,0 +1,289 @@ +# πŸ” Smart Door Lock - RFID/NFC Access Control + +**Contributor:** SOHAM-GADEKAE +**Domain:** IoT +**Difficulty:** Intermediate +**Tech Stack:** Arduino, RFID, Servo, LCD, C++ + +--- + +## πŸ“ Description + +A comprehensive Smart Door Lock system using RFID/NFC technology for secure access control. Features multiple authorized cards, servo motor door control, LCD status display, audio feedback, and LED indicators. Perfect for learning IoT security concepts and hardware integration! + +--- + +## 🎯 Features + +- βœ… **RFID/NFC Authentication** - Secure card-based access control +- βœ… **Multiple Authorized Cards** - Support for up to 3 cards (expandable) +- βœ… **Servo Motor Lock** - Automated door locking mechanism +- βœ… **LCD Status Display** - Real-time system status and feedback +- βœ… **Audio Feedback** - Success/error sound notifications +- βœ… **LED Indicators** - Visual status (Green=Success, Red=Denied) +- βœ… **Manual Override** - Push button for manual unlock/lock +- βœ… **Auto-Lock Timer** - Automatic door locking after timeout +- βœ… **Access Logging** - Serial monitor logging of all access attempts +- βœ… **System Testing** - Startup self-test sequence +- βœ… **Debounced Input** - Reliable button and sensor readings + +--- + +## πŸ› οΈ Tech Stack + +- **Arduino Uno/Nano** - Main microcontroller +- **RC522 RFID Module** - Card reading and authentication +- **SG90 Servo Motor** - Door locking mechanism +- **16x2 LCD Display (I2C)** - Status display +- **Buzzer** - Audio feedback system +- **LEDs** - Visual status indicators +- **C++** - Arduino programming language +- **SPI Communication** - RFID module interface +- **I2C Communication** - LCD display interface + +--- + +## πŸš€ How to Run + +### Method 1: Arduino IDE + +1. **Install Arduino IDE** (latest version) +2. **Install Required Libraries**: + - MFRC522 (RFID) + - LiquidCrystal_I2C (LCD) + - Servo (built-in) +3. **Upload Code** to Arduino +4. **Connect Hardware** as per circuit diagram +5. **Power On** and test with RFID cards + +### Method 2: PlatformIO + +1. **Install PlatformIO** in VS Code +2. **Create New Project** for Arduino +3. **Add Libraries** to platformio.ini +4. **Upload and Monitor** + +--- + +## πŸ“ Project Structure + +``` +SmartDoorLock/ +β”œβ”€β”€ code.ino # Main Arduino code +β”œβ”€β”€ circuit_diagram.md # Wiring instructions +β”œβ”€β”€ README.md # This documentation +└── libraries/ # Required libraries + β”œβ”€β”€ MFRC522/ + └── LiquidCrystal_I2C/ +``` + +--- + +## πŸ’» Code Highlights + +### RFID Card Authentication +```cpp +void handleRFIDCard() { + String cardUID = getCardUID(); + Serial.println("Card detected: " + cardUID); + + if (isAuthorizedCard(cardUID)) { + grantAccess(); + logAccess(cardUID, true); + } else { + denyAccess(); + logAccess(cardUID, false); + } +} +``` + +### Servo Motor Control +```cpp +void grantAccess() { + doorLocked = false; + doorServo.write(90); // Unlocked position + digitalWrite(GREEN_LED, HIGH); + playSuccessSound(); +} +``` + +### Auto-Lock Timer +```cpp +void loop() { + // Auto-lock door after timeout + if (!doorLocked && millis() - doorOpenTime > DOOR_OPEN_DURATION) { + lockDoor(); + } +} +``` + +--- + +## πŸ“š Learning Outcomes + +### Skills Practiced +- βœ… **Hardware Integration** - Multiple sensors and actuators +- βœ… **SPI Communication** - RFID module interface +- βœ… **I2C Communication** - LCD display control +- βœ… **Servo Motor Control** - PWM-based positioning +- βœ… **Input Validation** - Card authentication logic +- βœ… **State Management** - Door lock states +- βœ… **Timing Control** - Auto-lock functionality +- βœ… **Audio/Visual Feedback** - User interface design + +### Concepts Learned +- RFID/NFC technology and protocols +- Servo motor control and positioning +- LCD display programming +- Hardware security systems +- Real-time system programming +- Sensor data processing +- Access control systems + +--- + +## πŸ”§ Hardware Setup + +### Required Components +- Arduino Uno/Nano +- RC522 RFID Module +- SG90 Servo Motor +- 16x2 LCD Display (I2C) +- Buzzer +- Green & Red LEDs +- Push Button +- Resistors (220Ξ©, 10kΞ©) +- Jumper Wires +- Breadboard + +### Wiring Instructions +See `circuit_diagram.md` for detailed wiring connections and circuit diagram. + +--- + +## πŸ”‘ Card Management + +### Adding New Cards +1. **Get Card UID**: Use the serial monitor to read card UIDs +2. **Update Code**: Add new UID to `authorizedCards[]` array +3. **Upload**: Re-upload code to Arduino +4. **Test**: Verify new card works + +### Current Authorized Cards +```cpp +String authorizedCards[] = { + "A1B2C3D4", // Card 1 + "E5F6G7H8", // Card 2 + "I9J0K1L2" // Card 3 +}; +``` + +--- + +## πŸŽ›οΈ System Controls + +### Automatic Features +- **Card Detection**: Automatic RFID scanning +- **Access Validation**: Real-time card verification +- **Auto-Lock**: 5-second timeout after unlock +- **Status Display**: Real-time LCD updates + +### Manual Controls +- **Push Button**: Manual unlock/lock toggle +- **Reset**: Power cycle for system reset +- **Serial Monitor**: Debug and logging output + +--- + +## πŸ“Š System States + +| State | Description | LED | Sound | LCD Display | +|-------|-------------|-----|-------|-------------| +| **Locked** | Door secured, waiting for card | Red OFF | None | "Scan your card" | +| **Access Granted** | Valid card detected | Green ON | Success tone | "Access Granted!" | +| **Access Denied** | Invalid card detected | Red ON | Error tone | "Access Denied!" | +| **Unlocked** | Door open, auto-lock countdown | Green ON | None | "Door: UNLOCKED" | + +--- + +## πŸ”§ Troubleshooting + +### Common Issues + +| Problem | Solution | +|---------|----------| +| **RFID not detected** | Check 3.3V power, SPI connections | +| **Servo not moving** | Verify 5V power, signal wire to Pin 6 | +| **LCD blank** | Check I2C address (0x27), power connections | +| **No sound** | Test buzzer connections, Pin 7 | +| **LEDs not working** | Check resistor values, polarity | +| **Button not responding** | Verify Pin 2 connection, internal pull-up | + +### Debug Mode +Enable serial monitoring at 9600 baud to see: +- Card UIDs +- Access attempts +- System status +- Error messages + +--- + +## 🎨 Customization Ideas + +Want to enhance this project? Try adding: + +1. **WiFi Integration** - Remote monitoring via ESP8266 +2. **Mobile App** - Bluetooth control via smartphone +3. **Camera Module** - Security recording on access +4. **PIR Sensor** - Motion detection integration +5. **Keypad Backup** - PIN code authentication +6. **Multiple Doors** - Control multiple locks +7. **Time-based Access** - Scheduled access control +8. **Database Logging** - Store access history +9. **Email Alerts** - Notification system +10. **Voice Commands** - Speech recognition + +--- + +## πŸš€ Future Enhancements + +- [ ] **Web Dashboard** - Remote monitoring interface +- [ ] **Mobile App** - Smartphone control +- [ ] **Database Integration** - Access history storage +- [ ] **Multi-User Support** - User management system +- [ ] **Time Scheduling** - Time-based access control +- [ ] **Biometric Integration** - Fingerprint authentication +- [ ] **Cloud Connectivity** - IoT platform integration +- [ ] **Advanced Security** - Encryption and secure protocols + +--- + +## ⚠️ Safety Notes + +- **Power Supply**: Use regulated 5V supply (1A recommended) +- **Servo Mounting**: Ensure proper mechanical mounting +- **RFID Module**: Use 3.3V only (5V will damage the module) +- **Wiring**: Double-check all connections before powering on +- **Testing**: Test each component individually first +- **Security**: Change default card UIDs for production use + +--- + +## πŸ“„ License + +MIT License - Free to use and modify! + +--- + +## 🀝 Contributing + +This is a sample project for ProjectHive. Feel free to: +- Fork and enhance +- Report issues +- Suggest improvements +- Use as learning material +- Add new features + +--- + +**Happy Building! πŸ”βœ¨** diff --git a/Domains/IoT/MiniProjects/SmartDoorLock/circuit_diagram.md b/Domains/IoT/MiniProjects/SmartDoorLock/circuit_diagram.md new file mode 100644 index 00000000..c2d074bc --- /dev/null +++ b/Domains/IoT/MiniProjects/SmartDoorLock/circuit_diagram.md @@ -0,0 +1,198 @@ +# πŸ”Œ Smart Door Lock - Circuit Diagram & Wiring + +## πŸ“‹ Components Required + +| Component | Quantity | Purpose | +|-----------|----------|---------| +| Arduino Uno/Nano | 1 | Main controller | +| RC522 RFID Module | 1 | Card reading | +| SG90 Servo Motor | 1 | Door lock mechanism | +| 16x2 LCD Display (I2C) | 1 | Status display | +| Buzzer | 1 | Audio feedback | +| Green LED | 1 | Success indicator | +| Red LED | 1 | Error indicator | +| Push Button | 1 | Manual unlock | +| Resistors (220Ξ©, 10kΞ©) | 3 | Current limiting | +| Jumper Wires | - | Connections | +| Breadboard | 1 | Prototyping | + +## πŸ”— Wiring Connections + +### Arduino Pin Connections + +| Component | Arduino Pin | Notes | +|-----------|-------------|-------| +| **RC522 RFID Module** | | | +| VCC | 3.3V | Power supply | +| GND | GND | Ground | +| RST | Pin 9 | Reset pin | +| SS | Pin 10 | Slave select | +| MOSI | Pin 11 | SPI communication | +| MISO | Pin 12 | SPI communication | +| SCK | Pin 13 | SPI clock | +| **Servo Motor** | | | +| Signal | Pin 6 | PWM control | +| VCC | 5V | Power supply | +| GND | GND | Ground | +| **LCD Display (I2C)** | | | +| VCC | 5V | Power supply | +| GND | GND | Ground | +| SDA | A4 | I2C data | +| SCL | A5 | I2C clock | +| **Buzzer** | | | +| Positive | Pin 7 | Digital output | +| Negative | GND | Ground | +| **Green LED** | | | +| Anode | Pin 3 | Digital output | +| Cathode | GND (via 220Ξ© resistor) | Current limiting | +| **Red LED** | | | +| Anode | Pin 4 | Digital output | +| Cathode | GND (via 220Ξ© resistor) | Current limiting | +| **Push Button** | | | +| One terminal | Pin 2 | Digital input | +| Other terminal | GND | Ground | +| **Pull-up Resistor** | | | +| 10kΞ© | Pin 2 to 5V | Internal pull-up used | + +## πŸ”Œ Circuit Diagram + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”‚ Arduino Uno β”‚ + β”‚ β”‚ + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ 3.3V GND β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”‚ β”‚ β”‚ β”‚ + β”‚ β”‚ Pin 9 Pin 10 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ + β”‚ β”‚ β”‚ β”‚ + β”‚ β”‚ Pin 11 Pin 12 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ + β”‚ β”‚ β”‚ β”‚ + β”‚ β”‚ Pin 13 Pin 6 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ + β”‚ β”‚ β”‚ β”‚ + β”‚ β”‚ Pin 7 Pin 3 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ + β”‚ β”‚ β”‚ β”‚ + β”‚ β”‚ Pin 4 Pin 2 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ + β”‚ β”‚ β”‚ β”‚ + β”‚ β”‚ A4 A5 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ + β”‚ β”‚ β”‚ β”‚ + β”‚ β”‚ 5V GND β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ + └──────────────── β”‚ β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ + β”‚ + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ + β”‚ RC522 RFID β”‚ β”‚ SG90 Servo β”‚ β”‚ 16x2 LCD β”‚ β”‚ + β”‚ Module β”‚ β”‚ Motor β”‚ β”‚ (I2C) β”‚ β”‚ + β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ + β”‚ VCC ────────┼─── 3.3V β”‚ β”‚ VCC ────────┼─── 5V + β”‚ GND ────────┼─── GND β”‚ β”‚ GND ────────┼─── GND + β”‚ RST ────────┼─── Pin 9 β”‚ β”‚ SDA ────────┼─── A4 + β”‚ SS ─────────┼─── Pin 10 β”‚ β”‚ SCL ────────┼─── A5 + β”‚ MOSI ───────┼─── Pin 11 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ + β”‚ MISO ───────┼─── Pin 12 β”‚ β”‚ + β”‚ SCK ────────┼─── Pin 13 β”‚ β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ + β”‚ Signal ─────┼─── Pin 6 β”‚ + β”‚ VCC ────────┼─── 5V β”‚ + β”‚ GND ────────┼─── GND β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ + β”‚ + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ + β”‚ Buzzer β”‚ β”‚ Green LED β”‚ β”‚ Red LED β”‚ β”‚ + β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ + β”‚ + ──────────┼─── Pin 7 β”‚ β”‚ + ──────────┼─── Pin 3 + β”‚ - ──────────┼─── GND β”‚ β”‚ - ──────────┼─── GND + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β”‚ β”‚ + β”‚ + ──────────┼─── Pin 4 β”‚ β”‚ + β”‚ - ──────────┼─── GND β”‚ β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ + β”‚ + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ + β”‚Push Button β”‚ β”‚ + β”‚ β”‚ β”‚ + β”‚ ────────────┼─── Pin 2 β”‚ + β”‚ ────────────┼─── GND β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ + β”‚ + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ + β”‚ 10kΞ© Resistorβ”‚ β”‚ + β”‚ β”‚ β”‚ + β”‚ ────────────┼─── Pin 2 to 5V (Optional) β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ + β”‚ + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ + β”‚ 220Ξ© Resistorsβ”‚ β”‚ + β”‚ (2x) β”‚ β”‚ + β”‚ β”‚ β”‚ + β”‚ ────────────┼─── LED Anodes β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ + β”‚ + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ + β”‚ GND Rail β”‚ β”‚ + β”‚ β”‚ β”‚ + β”‚ β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +## ⚑ Power Requirements + +- **Arduino Uno**: 5V, ~100mA +- **RC522 Module**: 3.3V, ~50mA +- **Servo Motor**: 5V, ~200mA (peak) +- **LCD Display**: 5V, ~20mA +- **Buzzer**: 5V, ~30mA +- **LEDs**: 5V, ~20mA each + +**Total Current**: ~420mA (recommend 1A power supply) + +## πŸ”§ Assembly Steps + +1. **Power Connections** + - Connect 5V and GND rails on breadboard + - Connect Arduino 5V to breadboard 5V rail + - Connect Arduino GND to breadboard GND rail + +2. **RFID Module** + - Connect RC522 to Arduino as per pin mapping + - Ensure 3.3V power supply (not 5V!) + +3. **Servo Motor** + - Connect signal wire to Pin 6 + - Connect power to 5V and GND + - Test servo movement before mounting + +4. **LCD Display** + - Connect I2C pins (SDA to A4, SCL to A5) + - Connect power (5V, GND) + +5. **LEDs and Buzzer** + - Connect with appropriate resistors + - Test each component individually + +6. **Push Button** + - Connect to Pin 2 and GND + - Use internal pull-up resistor + +## ⚠️ Safety Notes + +- **Power Supply**: Use regulated 5V supply (1A recommended) +- **Servo Motor**: Ensure proper mounting to prevent damage +- **RFID Module**: Use 3.3V only (5V will damage it) +- **Wiring**: Double-check all connections before powering on +- **Testing**: Test each component individually first + +## πŸ” Troubleshooting + +| Issue | Solution | +|-------|----------| +| RFID not detected | Check 3.3V power, SPI connections | +| Servo not moving | Check 5V power, signal wire | +| LCD not displaying | Check I2C address, power connections | +| LEDs not working | Check resistor values, polarity | +| Buzzer not working | Check power, signal connections | + +## πŸ“± Optional Enhancements + +- **WiFi Module (ESP8266)**: Remote monitoring +- **Camera Module**: Security recording +- **PIR Sensor**: Motion detection +- **Keypad**: PIN code backup +- **Bluetooth Module**: Mobile app control diff --git a/Domains/IoT/MiniProjects/SmartDoorLock/code.ino b/Domains/IoT/MiniProjects/SmartDoorLock/code.ino new file mode 100644 index 00000000..b47978af --- /dev/null +++ b/Domains/IoT/MiniProjects/SmartDoorLock/code.ino @@ -0,0 +1,311 @@ +/* + * Smart Door Lock - RFID/NFC Access Control System + * + * Features: + * - RFID/NFC card authentication + * - Servo motor door lock control + * - LCD display for status + * - Buzzer for audio feedback + * - LED indicators + * - Multiple authorized cards + * - Access logging + * + * Hardware Required: + * - Arduino Uno/Nano + * - RC522 RFID Module + * - Servo Motor (SG90) + * - 16x2 LCD Display + * - Buzzer + * - LEDs (Green, Red) + * - Resistors + * - Jumper wires + * + */ + +#include +#include +#include +#include +#include + +// Pin definitions +#define RST_PIN 9 +#define SS_PIN 10 +#define SERVO_PIN 6 +#define BUZZER_PIN 7 +#define GREEN_LED 3 +#define RED_LED 4 +#define BUTTON_PIN 2 + +// Initialize components +MFRC522 mfrc522(SS_PIN, RST_PIN); +LiquidCrystal_I2C lcd(0x27, 16, 2); +Servo doorServo; + +// Door states +bool doorLocked = true; +bool accessGranted = false; + +// Authorized card UIDs (replace with your card UIDs) +String authorizedCards[] = { + "A1B2C3D4", // Card 1 + "E5F6G7H8", // Card 2 + "I9J0K1L2" // Card 3 +}; +int numAuthorizedCards = 3; + +// Timing variables +unsigned long lastAccessTime = 0; +unsigned long doorOpenTime = 0; +const unsigned long DOOR_OPEN_DURATION = 5000; // 5 seconds + +// Button debouncing +unsigned long lastButtonPress = 0; +const unsigned long DEBOUNCE_DELAY = 200; + +void setup() { + Serial.begin(9600); + + // Initialize SPI and RFID + SPI.begin(); + mfrc522.PCD_Init(); + + // Initialize LCD + lcd.init(); + lcd.backlight(); + + // Initialize servo + doorServo.attach(SERVO_PIN); + doorServo.write(0); // Locked position + + // Initialize pins + pinMode(BUZZER_PIN, OUTPUT); + pinMode(GREEN_LED, OUTPUT); + pinMode(RED_LED, OUTPUT); + pinMode(BUTTON_PIN, INPUT_PULLUP); + + // Initial display + lcd.clear(); + lcd.setCursor(0, 0); + lcd.print("Smart Door Lock"); + lcd.setCursor(0, 1); + lcd.print("Scan your card"); + + Serial.println("Smart Door Lock System Started"); + Serial.println("Scan your RFID card..."); + + // Test sequence + performStartupTest(); +} + +void loop() { + // Check for RFID card + if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()) { + handleRFIDCard(); + delay(1000); // Prevent multiple reads + } + + // Check for manual unlock button + if (digitalRead(BUTTON_PIN) == LOW && millis() - lastButtonPress > DEBOUNCE_DELAY) { + lastButtonPress = millis(); + handleManualUnlock(); + } + + // Auto-lock door after timeout + if (!doorLocked && millis() - doorOpenTime > DOOR_OPEN_DURATION) { + lockDoor(); + } + + // Update display + updateDisplay(); + + delay(100); +} + +void handleRFIDCard() { + String cardUID = getCardUID(); + Serial.println("Card detected: " + cardUID); + + // Check if card is authorized + if (isAuthorizedCard(cardUID)) { + grantAccess(); + logAccess(cardUID, true); + } else { + denyAccess(); + logAccess(cardUID, false); + } +} + +String getCardUID() { + String cardUID = ""; + for (byte i = 0; i < mfrc522.uid.size; i++) { + if (mfrc522.uid.uidByte[i] < 0x10) { + cardUID += "0"; + } + cardUID += String(mfrc522.uid.uidByte[i], HEX); + } + cardUID.toUpperCase(); + return cardUID; +} + +bool isAuthorizedCard(String cardUID) { + for (int i = 0; i < numAuthorizedCards; i++) { + if (cardUID == authorizedCards[i]) { + return true; + } + } + return false; +} + +void grantAccess() { + accessGranted = true; + doorLocked = false; + doorOpenTime = millis(); + + // Unlock door + doorServo.write(90); // Unlocked position + + // Visual and audio feedback + digitalWrite(GREEN_LED, HIGH); + digitalWrite(RED_LED, LOW); + playSuccessSound(); + + // Display success message + lcd.clear(); + lcd.setCursor(0, 0); + lcd.print("Access Granted!"); + lcd.setCursor(0, 1); + lcd.print("Door Unlocked"); + + Serial.println("Access Granted - Door Unlocked"); +} + +void denyAccess() { + accessGranted = false; + + // Visual and audio feedback + digitalWrite(GREEN_LED, LOW); + digitalWrite(RED_LED, HIGH); + playErrorSound(); + + // Display error message + lcd.clear(); + lcd.setCursor(0, 0); + lcd.print("Access Denied!"); + lcd.setCursor(0, 1); + lcd.print("Unauthorized Card"); + + Serial.println("Access Denied - Unauthorized Card"); +} + +void lockDoor() { + doorLocked = true; + accessGranted = false; + + // Lock door + doorServo.write(0); // Locked position + + // Turn off LEDs + digitalWrite(GREEN_LED, LOW); + digitalWrite(RED_LED, LOW); + + Serial.println("Door Auto-Locked"); +} + +void handleManualUnlock() { + if (doorLocked) { + grantAccess(); + Serial.println("Manual Unlock Activated"); + } else { + lockDoor(); + Serial.println("Manual Lock Activated"); + } +} + +void playSuccessSound() { + // Success melody + tone(BUZZER_PIN, 1000, 200); + delay(200); + tone(BUZZER_PIN, 1500, 200); + delay(200); + tone(BUZZER_PIN, 2000, 200); +} + +void playErrorSound() { + // Error melody + tone(BUZZER_PIN, 300, 500); + delay(100); + tone(BUZZER_PIN, 200, 500); +} + +void updateDisplay() { + static unsigned long lastDisplayUpdate = 0; + + if (millis() - lastDisplayUpdate > 1000) { + lastDisplayUpdate = millis(); + + if (doorLocked) { + lcd.clear(); + lcd.setCursor(0, 0); + lcd.print("Door: LOCKED"); + lcd.setCursor(0, 1); + lcd.print("Scan card to open"); + } else { + lcd.clear(); + lcd.setCursor(0, 0); + lcd.print("Door: UNLOCKED"); + lcd.setCursor(0, 1); + lcd.print("Auto-lock in: "); + int remainingTime = (DOOR_OPEN_DURATION - (millis() - doorOpenTime)) / 1000; + if (remainingTime > 0) { + lcd.print(remainingTime); + lcd.print("s"); + } + } + } +} + +void logAccess(String cardUID, bool granted) { + // Simple logging to Serial + Serial.print("Access Log - "); + Serial.print(millis()); + Serial.print(" - Card: "); + Serial.print(cardUID); + Serial.print(" - "); + Serial.println(granted ? "GRANTED" : "DENIED"); + + // You can extend this to save to EEPROM or send to server +} + +void performStartupTest() { + // Test sequence on startup + lcd.clear(); + lcd.setCursor(0, 0); + lcd.print("System Test..."); + + // Test LEDs + digitalWrite(GREEN_LED, HIGH); + delay(500); + digitalWrite(GREEN_LED, LOW); + digitalWrite(RED_LED, HIGH); + delay(500); + digitalWrite(RED_LED, LOW); + + // Test servo + doorServo.write(90); + delay(500); + doorServo.write(0); + + // Test buzzer + tone(BUZZER_PIN, 1000, 200); + delay(200); + noTone(BUZZER_PIN); + + lcd.clear(); + lcd.setCursor(0, 0); + lcd.print("System Ready!"); + lcd.setCursor(0, 1); + lcd.print("Scan your card"); + + Serial.println("System startup test completed"); +}