#include <LiquidCrystal_I2C.h>
#include <Servo.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
Servo lockServo;
int ledR = 13;
int btnR = 2;
int ledG = 12;
int btnG = 3;
int ledB = 11;
int btnB = 4;
int buzzer = 10;
const int correctSequence[4] = {2, 3, 4, 2}; // Sequence: Red, Green, Blue, Red
int inputSequence[4];
int inputIndex = 0;
void setup() {
pinMode(btnR, INPUT_PULLUP);
pinMode(ledR, OUTPUT);
pinMode(btnG, INPUT_PULLUP);
pinMode(ledG, OUTPUT);
pinMode(btnB, INPUT_PULLUP);
pinMode(ledB, OUTPUT);
pinMode(buzzer, OUTPUT);
lockServo.attach(9); // Attach the servo to pin 9
lockServo.write(0); // Initial position (locked)
lcd.init();
lcd.backlight();
Serial.begin(9600);
lcd.setCursor(0, 0);
lcd.print("Enter Code:");
}
void loop() {
int valR = digitalRead(btnR);
int valG = digitalRead(btnG);
int valB = digitalRead(btnB);
if (valR == LOW) {
recordInput(2, ledR);
}
if (valG == LOW) {
recordInput(3, ledG);
}
if (valB == LOW) {
recordInput(4, ledB);
}
checkSequence();
}
void recordInput(int buttonID, int ledPin) {
if (inputIndex < 4) {
digitalWrite(ledPin, HIGH);
inputSequence[inputIndex] = buttonID;
inputIndex++;
soundBuzzer(1000);
delay(500);
digitalWrite(ledPin, LOW);
}
}
void checkSequence() {
if (inputIndex == 4) {
bool isCorrect = true;
for (int i = 0; i < 4; i++) {
if (inputSequence[i] != correctSequence[i]) {
isCorrect = false;
break;
}
}
if (isCorrect) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Unlocked!");
lockServo.write(90); // Move servo to unlocked position
soundBuzzer(1500);
delay(1000);
} else {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Incorrect!");
soundErrorTone();
delay(1000);
}
resetInput();
}
}
void resetInput() {
inputIndex = 0;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Enter Code:");
lockServo.write(0); // Move servo back to locked position
}
void soundBuzzer(int frequency) {
tone(buzzer, frequency);
delay(100);
noTone(buzzer);
}
void soundErrorTone() {
for (int i = 0; i < 1000; i++) {
tone(buzzer, 5000);
delay(100);
noTone(buzzer);
delay(100);
}
}