#include <Keypad.h>
#include <Servo.h>
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowPins[ROWS] = {9, 8, 7, 6};
byte colPins[COLS] = {5, 4, 3, 2};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
Servo lockServo;
const int greenPin = 10;
const int redPin = 11;
const int bluePin = 12;
const int changeButtonPin = A0;
const int openButtonPin = A1;
String correctCode = "1234";
String inputCode = "";
String newCode = "";
bool isChangeMode = false;
void setup() {
pinMode(greenPin, OUTPUT);
pinMode(redPin, OUTPUT);
pinMode(bluePin, OUTPUT);
pinMode(changeButtonPin, INPUT_PULLUP);
pinMode(openButtonPin, INPUT_PULLUP);
lockServo.attach(13);
lockServo.write(0);
Serial.begin(9600);
}
void loop() {
char key = keypad.getKey();
if (digitalRead(openButtonPin) == LOW) {
lockServo.write(90);
delay(1000);
lockServo.write(0);
}
if (digitalRead(changeButtonPin) == LOW) {
isChangeMode = true;
newCode = "";
setLEDColor(0, 0, 255);
}
if (key && isChangeMode) {
if (key == '*') {
if (newCode.length() == 4) {
correctCode = newCode;
setLEDColor(0, 255, 0);
delay(1000);
setLEDColor(0, 0, 0);
}
isChangeMode = false;
} else if (key >= '0' && key <= '9') {
newCode += key;
}
} else if (key) {
if (key == '#') {
if (inputCode == correctCode) {
setLEDColor(0, 255, 0);
lockServo.write(90);
delay(1000);
lockServo.write(0);
} else {
setLEDColor(255, 0, 0);
}
inputCode = "";
delay(1000);
setLEDColor(0, 0, 0);
} else if (key >= '0' && key <= '9') {
inputCode += key;
}
}
}
void setLEDColor(int red, int green, int blue) {
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}