#include <Wire.h> 
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);  // Set the LCD address to 0x27 for a 16 chars and 2 line display

const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] = {
  {'1','4','7','*'},
  {'2','5','8','0'},
  {'3','6','9','#'},
  {'A','B','C','D'}
};

// char keys[ROWS][COLS] = {
//   {'1','2','3','A'},
//   {'4','5','6','B'},
//   {'7','8','9','C'},
//   {'*','0','#','D'}
// };

byte rowPins[ROWS] = {8, 9, 10, 11}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {4, 5, 6, 7}; //connect to the column pinouts of the keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

int inputNumber;

void setup() {
  lcd.init();                      // initialize the lcd 
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("Input 1 to 20");
  randomSeed(analogRead(0)); // Seed the random number generator with an analog pin reading
}

void loop() {
  char key = keypad.getKey();
  
  if (key != NO_KEY && (key >= '0' && key <= '9')) {
    inputNumber = inputNumber * 10 + (key - '0');
    if (inputNumber > 20) {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Error");
      delay(2000); // Display "Error" for 2 seconds
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Input 1 to 20");
      inputNumber = 0;
    } else {
      lcd.setCursor(0, 1);
      lcd.print("Input: ");
      lcd.print(inputNumber);
    }
  }
  
  if (key == 'C') {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Input 1 to 20");
    inputNumber = 0;
  }
  
  if (key == 'D') {
    lcd.clear();
    lcd.setCursor(0, 0);
    if (inputNumber <= 20) {
      lcd.print("Random Number:");
      int randomNumber = random(1, inputNumber + 1); // Random number between 1 and inputNumber
     lcd.setCursor(0, 1); 
      lcd.print(randomNumber);
    } else {
      lcd.print("Error");
      delay(2000); // Display "Error" for 2 seconds
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Input 1 to 20");
    }
  }
}
