#include <Keypad.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
// Declare the Servo pin
int servoPin = 4;
// Create a servo object
Servo Servo1;
#define KEY_ROWS 4 // Keypad rows
#define KEY_COLS 4 // Keypad columns
#define LCD_ROWS 2 // LCD rows
#define LCD_COLS 16 // LCD columns
// 設置按鍵模組
char keymap[KEY_ROWS][KEY_COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowPins[KEY_ROWS] = {13, 12, 11, 10};
byte colPins[KEY_COLS] = {9, 8, 7, 6};
Keypad keypad = Keypad(makeKeymap(keymap), rowPins, colPins, KEY_ROWS, KEY_COLS);
String passcode = "2580"; // Setting password
String inputCode = ""; // Save the password
bool acceptKey = true; // Accepting the password entered
LiquidCrystal_I2C lcd(0x27, 16, 2);
void clearRow(byte n) {
byte last = LCD_COLS - n;
lcd.setCursor(n, 1); // Change to the 2nd row, then prints "Pin:"
for (byte i = 0; i < last; i++) {
lcd.print(" ");
}
lcd.setCursor(n, 1);
}
void resetLocker() {
lcd.clear();
lcd.print("Get Some Food");
lcd.setCursor(0, 1); // Change to the 2nd row
lcd.print("PIN:");
lcd.cursor();
Servo1.write(40); //The servo locks
acceptKey = true;
inputCode = "";
}
void unlockdoor(){ //controls servo that locks the door
Servo1.write(110); //Degree when the lock opens
lcd.setCursor(0,1);
clearRow(0);
lcd.print("**** PASS! ****");
delay(1500); //To make sure the LCD receives the message
}
void checkPinCode() {
acceptKey = false; // Not accepting any enter for passcode
clearRow(0); // Clear from the 0 numer
lcd.noCursor();
lcd.setCursor(0, 1); // Change to the 2nd row
// Check the passcode
if (inputCode == passcode) {
lcd.print("**** PASS! ****");
unlockdoor();
} else {
lcd.print("WRONG! Try Again!");
}
delay(7000);
resetLocker(); // Reset LCD and servo
}
void setup() {
digitalWrite( 5 , LOW );
Serial.begin(9600);
lcd.init();
lcd.backlight();
Servo1.attach(servoPin);
Servo1.write(40); //Degree when the servo locks
resetLocker();
}
void loop() {
char key = keypad.getKey();
if (acceptKey && key != NO_KEY) {
if (key == '*') { // Clear
clearRow(4); // Clear from the 4th row
inputCode = "";
} else if (key == '#') { // Check passcode
checkPinCode();
} else {
inputCode += key; // Save
lcd.print('*');
}
}
}