#include <Servo.h>
Servo myServo;
// Define pin numbers
const int buttonPins[9] = {2, 3, 4, 5, 6, 7, 8, 9, 10};
const int redPins[3] = {12, 13, A0};
const int greenPins[3] = {A1, A2, A3};
// Define the correct PIN
const int correctPIN[4] = {1, 2, 3, 4}; // Change this to your desired PIN
// Variables to store the entered PIN and attempts
int enteredPIN[4];
int pinIndex = 0;
int attempt = 0;
void setup() {
Serial.begin(9600);
// Initialize button pins
for (int i = 0; i < 9; i++) {
pinMode(buttonPins[i], INPUT_PULLUP);
}
// Initialize LED pins
for (int i = 0; i < 3; i++) {
pinMode(redPins[i], OUTPUT);
pinMode(greenPins[i], OUTPUT);
}
// Attach the servo to pin 11
myServo.attach(11);
myServo.write(90); // Initial position (locked)
Serial.println("System Start");
}
void loop() {
// Read button presses
for (int i = 0; i < 9; i++) {
if (digitalRead(buttonPins[i]) == LOW) {
delay(50); // Debounce delay
while (digitalRead(buttonPins[i]) == LOW); // Wait for button release
enteredPIN[pinIndex] = i + 1;
pinIndex++;
Serial.print("Entered: ");
Serial.println(i + 1);
delay(200); // Debounce delay
}
}
// Check if 4 digits have been entered
if (pinIndex == 4) {
if (checkPIN()) {
// Correct PIN
Serial.println("Correct PIN! Unlocking door...");
myServo.write(180); // Unlock position
indicateSuccess();
delay(5000); // Keep the door unlocked for 5 seconds
myServo.write(90); // Lock position
resetSystem();
} else {
// Incorrect PIN
attempt++;
Serial.print("Incorrect PIN. Attempt ");
Serial.println(attempt);
indicateFailure();
if (attempt >= 3) {
Serial.println("Too many failed attempts. Locking system for 1 minute...");
blinkRedLEDs(60000); // Blink for 1 minute
attempt = 0;
}
resetSystem();
}
}
}
bool checkPIN() {
for (int i = 0; i < 4; i++) {
if (enteredPIN[i] != correctPIN[i]) {
return false;
}
}
return true;
}
void resetSystem() {
pinIndex = 0;
for (int i = 0; i < 4; i++) {
enteredPIN[i] = 0;
}
delay(1000); // Short delay before next input
}
void indicateSuccess() {
for (int i = 0; i < 3; i++) {
digitalWrite(greenPins[i], HIGH);
}
delay(5000); // Keep LEDs on for 5 seconds
for (int i = 0; i < 3; i++) {
digitalWrite(greenPins[i], LOW);
}
}
void indicateFailure() {
for (int i = 0; i < attempt; i++) {
digitalWrite(redPins[i], HIGH);
}
delay(1000); // Keep LEDs on for 1 second
for (int i = 0; i < attempt; i++) {
digitalWrite(redPins[i], LOW);
}
}
void blinkRedLEDs(unsigned long duration) {
unsigned long startTime = millis();
while (millis() - startTime < duration) {
for (int i = 0; i < 3; i++) {
digitalWrite(redPins[i], HIGH);
}
delay(500);
for (int i = 0; i < 3; i++) {
digitalWrite(redPins[i], LOW);
}
delay(500);
}
}