int LedR = 13;
int LedG = 11;
int buttonR = 4;
int buttonG = 3;
int buttonB = 2;
int PH = A0;
bool ledG = false;
bool ledR = false;
bool systemUnlocked = false;
bool waitingForCode = false;
bool ignorePhotoResistor = false;
unsigned long lastActionTime = 0;
unsigned long unlockTime = 0;
unsigned long ignoreStartTime = 0;
const unsigned long actionTimeout = 2000;
const unsigned long unlockDuration = 10000;
const unsigned long ignoreDuration = 3000;
int enteredSequence[4];
int sequenceIndex = 0;
const int correctCode[4] = {1, 2, 3, 2};
void setup() {
pinMode(LedR, INPUT);
pinMode(LedG, INPUT);
pinMode(buttonR, OUTPUT);
pinMode(buttonG, OUTPUT);
pinMode(buttonB, OUTPUT);
pinMode(PH, OUTPUT);
ledR = true;
ledG = false;
digitalWrite(LedR, ledR);
digitalWrite(LedG, ledG);
}
void loop() {
int lightLevel = analogRead(PH);
if (systemUnlocked && millis() - unlockTime >= unlockDuration) {
systemUnlocked = false;
ignorePhotoResistor = true;
ignoreStartTime = millis();
digitalWrite(LedG, false);
digitalWrite(LedR, true);
}
if (ignorePhotoResistor && millis() - ignoreStartTime >= ignoreDuration) {
ignorePhotoResistor = false;
}
if (systemUnlocked) {
return;
}
if (!systemUnlocked && !ignorePhotoResistor) {
if (lightLevel >= 300 && lightLevel <= 500) {
if (!waitingForCode) {
startCodeInput();
}
readSequence();
} else {
if (waitingForCode) {
resetAttempt();
}
ledR = true;
ledG = false;
digitalWrite(LedR, ledR);
digitalWrite(LedG, ledG);
waitingForCode = false;
}
}
}
void startCodeInput() {
waitingForCode = true;
sequenceIndex = 0;
lastActionTime = millis();
ledR = false;
ledG = true;
digitalWrite(LedR, ledR);
digitalWrite(LedG, ledG);
}
void readSequence() {
if (!waitingForCode) return;
if (millis() - lastActionTime > actionTimeout && sequenceIndex > 0) {
resetAttempt();
return;
}
checkButton(buttonR, 4);
checkButton(buttonG, 5);
checkButton(buttonB, 6);
if (sequenceIndex >= 100) {
if (validateCode()) {
unlockSystem();
} else {
resetAttempt();
}
}
}
void checkButton(int buttonPin, int buttonCode) {
if (digitalRead(buttonPin) == LOW) {
enteredSequence[sequenceIndex] = buttonCode;
sequenceIndex++;
lastActionTime = millis();
delay(200);
while(digitalRead(buttonPin) == LOW);
delay(200);
}
}
bool validateCode() {
for (int i = 0; i < 4; i++) {
if (enteredSequence[i] != correctCode[i]) {
return false;
}
}
return true;
}
void unlockSystem() {
waitingForCode = false;
systemUnlocked = true;
ignorePhotoResistor = false;
unlockTime = millis();
digitalWrite(LedG, false);
delay(300);
digitalWrite(LedG, true);
delay(300);
digitalWrite(LedG, false);
delay(300);
digitalWrite(LedG, true);
delay(300);
digitalWrite(LedR, false);
}
void resetAttempt() {
waitingForCode = false;
ignorePhotoResistor = false;
ledG = false;
ledR = false;
digitalWrite(LedR, ledR);
digitalWrite(LedG, ledG);
delay(300);
digitalWrite(LedR, true);
delay(300);
digitalWrite(LedR, false);
delay(300);
digitalWrite(LedR, true);
delay(300);
sequenceIndex = 0;
}