const int debounceTime = 20;
const byte ROWS = 4; 
const byte COLS = 4;
String pass="2024A" ;
String inPass;
int ledR=10;
int ledG=11;
char keymap[ROWS][COLS] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};

byte rowPins[ROWS] = {9, 8, 7, 6}; 
byte colPins[COLS] = {5, 4, 3, 2}; 

 int index;
void setup() {
 Serial.begin(9600);
 for (int row = 0; row < ROWS; row++)
 {
 pinMode(rowPins[row],INPUT_PULLUP); 
 }
 for (int column = 0; column < COLS; column++)
 {
 pinMode(colPins[column],OUTPUT);
 digitalWrite(colPins[column],HIGH); 
 }
 pinMode(ledR, OUTPUT);
 pinMode(ledG, OUTPUT);

 
}

void loop() {
   digitalWrite(ledR, HIGH);
    digitalWrite(ledG, LOW);
  char key = getKey();
  
  if (key != 0) { 
    Serial.print("Got key: ");
    Serial.println(key);
    
    inPass += key;
    
    if (key == '#') {
      index=inPass.indexOf("#");
      inPass.remove(index);
      Serial.println("The Entered password is: " + inPass);
      if (inPass.equals(pass)) {
        Serial.println("It's the Correct Password!");
        digitalWrite(ledG, HIGH);
        digitalWrite(ledR, LOW);
        delay(3000);
      }
      else {
        Serial.println("SORRY!!..Incorrect Password!");
        digitalWrite(ledG, LOW);
        digitalWrite(ledR, HIGH);
        delay(3000);
        digitalWrite(ledR, LOW);
      }
      inPass = ""; 
    }
  }
}

char getKey()
{
 char key = 0;
 for(int column = 0; column < COLS; column++)
 {
 digitalWrite(colPins[column],LOW); 
 for(int row = 0; row < ROWS; row++) 
 {
 if(digitalRead(rowPins[row]) == LOW)
 {
 delay(debounceTime);
 while(digitalRead(rowPins[row]) == LOW); 
 key = keymap[row][column]; 
 }
 }
 digitalWrite(colPins[column],HIGH); 
 }
 return key; 

}