keypad scanning and multiple simultaneous keypresses detection

I have a standard keypad with the buttons wired by columns and rows. To scan I use the following approach: The columns are set to inputs with pull-ups. The rows are High-Z. To scan a row it is driven LOW and the columns are read. If a button on the scanned row is pressed the corresponding column is driven LOW otherwise it is pulled HIGH. Furthermore buttons in other rows should have no effect as they are HIGH-Z.

I tried implementing this on a 2x2 keymap:

// keypad

#define ROWS 2
#define COLS 2

int rowPins[ROWS] = { 2, 3 };
int colPins[COLS] = { 4, 5 };
int keypad_state[ROWS][COLS];

void keypad_init ()
{
  // set rows to HIGH Z
  for (int i = 0; i < ROWS; i++) {
    pinMode (rowPins[i], INPUT);
    digitalWrite (rowPins[i], LOW);
  }

  // set cols to input with pullups
  for (int j = 0; j < COLS; j++) {
    pinMode (colPins[j], INPUT);
    digitalWrite (colPins[j], HIGH);
  }
  
  for (int i = 0; i < ROWS; i++) {
    for (int j = 0; j < COLS; j++) {
      keypad_state[i][j] = 0;
    }
  }
}

void keypad_scan ()
{
  for (int i = 0; i < ROWS; i++) {
    // set row to LOW
    pinMode (rowPins[i], OUTPUT);

    for (int j = 0; j < COLS; j++) {
      int val = digitalRead (colPins[j]);
      keypad_state[i][j] = (val == LOW);
    }

    // set row to High Z
    pinMode (rowPins[i], INPUT);
  }
}

void setup ()
{
  Serial.begin(115200);
  keypad_init ();
}

void loop ()
{
  keypad_scan ();
  
  for (int i = 0; i < ROWS; i++) {
    for (int j = 0; j < COLS; j++) {
      Serial.print (keypad_state[i][j]);
      Serial.print (' ');
    }
    Serial.print ('\n');
  }
  Serial.print ('\n');
  
 delay (100);
}

If I maintain 0, 1, 2 or 4 buttons pressed they are detected correctly. However if I press any three the code reads all four as pressed.

Any idea on what the problem is ?
Thanks.

When enough keys are pressed to create connectivity between separate scan lines, the keyboard scan code will see extra “ghost” switch closures.
Ghosting and masking are going to happen with a simple keyboard matrix scanning approach. To avoid this, you will need diodes incorporated into the keypad matrix.

Have a look at this write-up: http://www.dribin.org/dave/keyboard/one_html/

Thanks. I was able to understand and correct the problem.

However this solution requires one diode per switch. That's fine with a custom keypad but I am looking into acquiring a larger pre-made one. It seems that commonly available keypads don't have embedded diodes. Any idea on where to get one ?