#include <Keypad.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 20, 4);
//keypad rows and columns
const int ROW_NUM = 4; //four rows
const int COLUMN_NUM = 4; //four columns
char keys[ROW_NUM][COLUMN_NUM] = {
{'1','2','3', 'A'},
{'4','5','6', 'B'},
{'7','8','9', 'C'},
{'*','0','#', 'D'}
};
//pins are swapped on IRL keypad,
//byte pin_rows[ROW_NUM] = {7, 6, 5, 4};
//byte pin_column[COLUMN_NUM] = {11, 10, 9, 8};
byte pin_rows[ROW_NUM] = {11, 10, 9, 8}; //connect to the row pinouts of the keypad
byte pin_column[COLUMN_NUM] = {7, 6, 5, 4}; //connect to the column pinouts of the keypad
char keyPress;
int numPress;
Keypad bKeypad = Keypad(makeKeymap(keys), pin_rows, pin_column, ROW_NUM, COLUMN_NUM );
const int codeLength = 10;
int colPos;
//the final input code of the user
String userCode;
//random digits for generating a codeS
int codeDigit[codeLength];
//code of all random digits put together
String gameCode;
int randNum = 0;
void setup() {
Serial.begin(9600);
randomSeed(analogRead(0));
// Initiate the LCD:
lcd.init();
lcd.backlight();
}
void loop() {
//planted state
//reset generated code
gameCode = ""; userCode = "";
colPos = (codeLength / 2);
//create code
//codeLength = 10, generate a 10 digit code
for (int i = 0; i < codeLength; i++){
codeDigit[i] = random(10);
//add the random digit to the code
gameCode = (gameCode + codeDigit[i]);
}
lcd.clear();
lcd.setCursor(colPos, 1);lcd.print("----------");
lcd.setCursor(colPos, 1);lcd.print(codeDigit[0]);
for (int i = 0; i < codeLength;){
keyPress = bKeypad.getKey();
if(keyPress){
//add key pressed to userCode
userCode = (userCode + keyPress);
lcd.setCursor(colPos + i, 2);lcd.print(keyPress);
i++;
//if the count is more than the array pointer, don't print
if (i < codeLength){
lcd.setCursor(colPos + i, 1);lcd.print(codeDigit[i]);
}
}
}
//if the codes match, move to next state
if (userCode == gameCode){
lcd.setCursor(0,0);
lcd.print("Planting bomb!");
delay(5000);
//return state 3
} else {
lcd.setCursor(0,0);
lcd.print("Code is incorrect.");
delay(5000);
// return state 1
}
}