//Keypad2
#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
const int buzz=11;
int ledr=13;
int ledg=12;
// Define the number of rows and columns of the keypad
const byte ROWS = 4; // Four rows
const byte COLS = 4; // Four columns
// Define the symbols on the buttons of the keypad
char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
// Connect keypad ROW0, ROW1, ROW2, ROW3 to Arduino pins
byte rowPins[ROWS] = {2,3,4,5};
// Connect keypad COL0, COL1, COL2, COL3 to Arduino pins
byte colPins[COLS] = {7,8,9,10};
// Create the Keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
const int PASSWORD_LENGTH = 5;
char password[PASSWORD_LENGTH] = "1234"; // Default password
char newPassword[PASSWORD_LENGTH];
char inputBuffer[PASSWORD_LENGTH];
int inputIndex = 0;
bool changePasswordMode = false;
bool enterPasswordMode = false;
bool buzzerActive = false;
void setup() {
Serial.begin(9600);
pinMode(buzz, OUTPUT);
lcd.begin(16, 2);
lcd.print("Welcome");
Serial.print("Welcome to smart home lock system!");
}
void loop() {
char key = keypad.getKey();
if (key) {
if (key == '*' && !enterPasswordMode) {
// Enter password mode
enterPasswordMode = true;
lcd.clear();
lcd.print("Enter Password:");
inputIndex = 0;
} else if (key == 'D' && enterPasswordMode && !changePasswordMode) {
// Enter change password mode
changePasswordMode = true;
lcd.clear();
lcd.print("New Password:");
inputIndex = 0;
} else if (key == '#' && changePasswordMode) {
// Confirm new password
if (inputIndex == PASSWORD_LENGTH - 1) {
strncpy(password, newPassword, PASSWORD_LENGTH);
lcd.clear();
lcd.print("Password Changed");
delay(2000);
lcd.clear();
lcd.print("Enter Password:");
} else {
lcd.clear();
lcd.print("Invalid Length");
delay(2000);
lcd.clear();
lcd.print("New Password:");
}
changePasswordMode = false;
inputIndex = 0;
} else if (key == '#' && !changePasswordMode) {
// Check the input password
if (strncmp(password, inputBuffer, PASSWORD_LENGTH - 1) == 0) {
lcd.clear();
lcd.print("Unlocked");
buzzerActive = false;
digitalWrite(buzz, LOW);
Serial.println(" Welcome home!");
digitalWrite(ledg,HIGH);
digitalWrite(ledr,LOW);
delay(10000);
lcd.clear();
lcd.print("Enter Password:");
} else {
buzzerActive = true;
lcd.clear();
lcd.print("Incorrect");
Serial.println("Intruder!");
digitalWrite(ledr,HIGH);
digitalWrite(ledg,LOW);
delay(5000);
lcd.clear();
lcd.print("Enter Password:");
}
inputIndex = 0;
} else if (key >= '0' && key <= '9' && inputIndex < PASSWORD_LENGTH - 1) {
// Collect input
lcd.setCursor(inputIndex, 1);
lcd.print('*'); // Display * for each entered digit
if (changePasswordMode) {
newPassword[inputIndex] = key;
} else {
inputBuffer[inputIndex] = key;
}
inputIndex++;
}
}
if (buzzerActive) {
digitalWrite(buzz, HIGH);
tone(buzz,1000);
} else {
digitalWrite(buzz, LOW);
noTone(buzz);
}
}