#include <Arduino.h>
// Keypad.h reads a matrix keypad without manually scanning every row and column.
#include <Keypad.h>

// The keypad has four rows and four columns; byte is an 8-bit unsigned type.
const byte ROWS = 4;
const byte COLS = 4;
// This two-dimensional array maps each row/column pair to the printed key label.
char keys[ROWS][COLS] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};
// These are the four Mega pins connected to the keypad row wires.
byte rowPins[ROWS] = {9, 8, 7, 6};
// These four pins connect to the column wires.
byte colPins[COLS] = {5, 4, 3, 2};
// Create a keypad object using the key map and those eight pin assignments.
Keypad keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

// Start Serial Monitor so each detected key can be shown on the computer.
void setup() {
  Serial.begin(9600);
}

void loop() {
  // getKey() returns the pressed key character, or no key when nothing new is detected.
  const char key = keypad.getKey();
  // Only print when a key value exists; avoid filling Serial with empty readings.
  if (key) Serial.println(key);
}
