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

const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {34, 19, 18, 5};
byte colPins[COLS] = {4, 2, 15, 12};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup() {
  lcd.init();
  lcd.backlight();
}

void loop() {
  char key = keypad.getKey();
  if (key) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Ban vua nhan: ");
    lcd.print(key);
    lcd.setCursor(0, 1);
    lcd.print("So lan: ");
    lcd.print(getCount(key));
  }
}

int getCount(char key) {
  static int count[ROWS][COLS] = {0};
  for (byte r = 0; r < ROWS; r++) {
    for (byte c = 0; c < COLS; c++) {
      if (keys[r][c] == key) {
        count[r][c]++;
        return count[r][c];
      }
    }
  }
  return 0;
}