const int xPin = A0;
const int yPin = A1;
const int swPin = 2;
const int redLED = 9;
const int greenLED = 10;
const int buzzer = 11;
const char password[] = {'U', 'R', 'D', 'L', 'B'};
const int passwordLength = sizeof(password) / sizeof(password[0]);
int currentStep = 0;
bool lastButton = HIGH;
bool inputLocked = false;
const int LOW_THRESHOLD = 300;
const int HIGH_THRESHOLD = 700;
void setup() {
pinMode(swPin, INPUT_PULLUP);
pinMode(redLED, OUTPUT);
pinMode(greenLED, OUTPUT);
pinMode(buzzer, OUTPUT);
Serial.begin(9600);
}
void loop() {
int x = analogRead(xPin);
int y = analogRead(yPin);
bool button = digitalRead(swPin);
char move = '\0';
char expected = password[currentStep];
if (!inputLocked) {
if (x < LOW_THRESHOLD) move = 'L';
else if (x > HIGH_THRESHOLD) move = 'R';
else if (y < LOW_THRESHOLD) move = 'U';
else if (y > HIGH_THRESHOLD) move = 'D';
else if (button == LOW && lastButton == HIGH) move = 'B';
}
lastButton = button;
if (move != '\0') {
Serial.print("Detected: ");
Serial.println(move);
beep(1, 100);
inputLocked = true;
// Check if input matches expected step
if (move == expected) {
currentStep++;
if (currentStep == passwordLength) {
success();
}
} else {
errorReset();
}
delay(300);
}
// Unlock input once joystick returns to center
if (inputLocked && x > LOW_THRESHOLD && x < HIGH_THRESHOLD &&
y > LOW_THRESHOLD && y < HIGH_THRESHOLD && button == HIGH) {
inputLocked = false;
}
}
void success() {
Serial.println("✅ Access Granted!");
digitalWrite(greenLED, HIGH);
digitalWrite(redLED, LOW);
beep(2, 200);
delay(1500);
digitalWrite(greenLED, LOW);
currentStep = 0;
}
void errorReset() {
Serial.println("❌ Wrong Input! Resetting...");
digitalWrite(redLED, HIGH);
digitalWrite(greenLED, LOW);
beep(1, 600);
delay(1500);
digitalWrite(redLED, LOW);
currentStep = 0;
}
void beep(int times, int duration) {
for (int i = 0; i < times; i++) {
tone(buzzer, 1000);
delay(duration);
noTone(buzzer);
delay(100);
}
}