int x = 0;
int a = 0;
int b = 0;
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
#include <Keypad.h>
const uint8_t ROWS = 4;
const uint8_t COLS = 4;
char keys[ROWS][COLS] = {
{ '1', '2', '3', 'A' },
{ '4', '5', '6', 'B' },
{ '7', '8', '9', 'C' },
{ '*', '0', '#', 'D' }
};
uint8_t colPins[COLS] = { 26, 25, 33, 32 }; // Pins connected to C1, C2, C3, C4
uint8_t rowPins[ROWS] = { 13, 12, 14, 27 }; // Pins connected to R1, R2, R3, R4
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
int pwa[4]; //輸入的數字轉成函數
int pw[4]; //隨機4位數的函數
String input_password;
void setup() {
Serial.begin(9600);
input_password.reserve(32);
lcd.init();
lcd.backlight();
lcd.setCursor(0, 1);
lcd.print("welcome to 1A2B");
ra();
}
void loop() {
delay(10);
char key = keypad.getKey();
lcd.setCursor(0, 0);
lcd.print(input_password);
const String password = String(pw[0]) + String(pw[1]) + String(pw[2]) + String(pw[3]);
//把函數轉成字串後相加
if (key) {
if (key == '*') {
input_password = ""; // clear input password
lcd.init();
}
else if (key == '#') {
a2b();
lcd.init();
if (password == input_password) {
Serial.println(input_password + " The password is correct, ACCESS GRANTED!");
lcd.setCursor(0, 1);
lcd.print(input_password+" you win !!!"); // DO YOUR WORK HERE
a=0; //把A跟B的記憶洗掉
b=0;
}
else {
Serial.println(input_password + " " +String(a)+"A"+String(b)+"B");
lcd.setCursor(0, 1);
lcd.print(String(a)+"A"+String(b)+"B");
input_password = ""; // clear input password
a=0;
b=0;
}
input_password = ""; // clear input password
}
else {
input_password += key; // append new character to input password string
int intpw = input_password.toInt(); //把input_password轉成整數
pwa[0] = intpw / 1000;
pwa[1] = (intpw - pwa[0] * 1000) / 100;
pwa[2] = (intpw - pwa[0] * 1000 - pwa[1] * 100) / 10;
pwa[3] = (intpw - pwa[0] * 1000 - pwa[1] * 100 - pwa[2] * 10);
for (int i = 0; i < 4; i++)
{
Serial.print(pwa[i]);
}
Serial.println("");
}
}
}
void ra() //隨機陣列
{
for (int i = 0; i < 4; i++)
{
x = random(0, 9);
while (x == pw[0] or x == pw[1] or x == pw[2] or x == pw[3])
{
x = random(0, 9);
}
pw[i] = x;
}
for (int i = 0; i < 4; i++)
{
Serial.print(pw[i]);
}
Serial.println("");
}
void a2b() //1A2B的判斷
{
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
if(pwa[i]==pw[j])
{
if(i==j)
{
a+=1;
}
else
{
b+=1;
}
}
}
}
}