/*
  03a_Keypad_SerialEcho

  4x4 matrix keypad test for an Arduino Uno R3 (5 V I/O)

  Wiring:
    D0-D3 -> rows 1-4 (top to bottom)
    D4-D7 -> columns 1-4 (left to right)

  Serial monitor at 9600 baud. Digits build up a number,
  * clears it, # enters it. A-D are reported but not added.

  D0 and D1 are also the USB serial pins, so Serial is only switched on
  while printing and the rest of the time they are plain row inputs.
  Don't hold a key down while uploading.
*/

// Keypad wiring and key layout, as printed on the pad.
const uint8_t ROW_PINS[] = {0, 1, 2, 3};
const uint8_t COL_PINS[] = {4, 5, 6, 7};
const uint8_t ROWS = sizeof(ROW_PINS);
const uint8_t COLS = sizeof(COL_PINS);

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

const unsigned long BAUD = 9600;   // slow enough to ignore scan pulses on D1
const uint8_t DEBOUNCE_MS = 20;        // a key must be steady this long
const uint8_t MAX_DIGITS = 16;

char number[MAX_DIGITS + 1];
uint8_t length = 0;

// Put the keypad row pins back to inputs with pull-ups. Needed after Serial
// has used D0 and D1.
void rowsAsInputs() {
  for (uint8_t r = 0; r < ROWS; ++r) pinMode(ROW_PINS[r], INPUT_PULLUP);
}

// Returns the first pressed key, or 0 if none. Columns float except
// while being scanned.
char scanKeypad() {
  char found = 0;
  for (uint8_t c = 0; c < COLS && !found; ++c) {
    digitalWrite(COL_PINS[c], LOW);
    pinMode(COL_PINS[c], OUTPUT);
    delayMicroseconds(5);
    for (uint8_t r = 0; r < ROWS; ++r) {
      if (digitalRead(ROW_PINS[r]) == LOW) {
        found = KEYS[r][c];
        break;
      }
    }
    pinMode(COL_PINS[c], INPUT);
  }
  return found;
}

// Print the key and the number typed so far. Zero prints the ready message.
void report(char key) {
  Serial.begin(BAUD);
  if (key == 0) {
    Serial.println(F("Keypad ready. * clears, # enters."));
  } else {
    Serial.print(F("Key: "));
    Serial.print(key);
    if (key == '*') {
      Serial.println(F("   cleared"));
    } else if (key == '#') {
      Serial.print(F("   ENTERED: "));
      Serial.println(number);
    } else {
      Serial.print(F("   Number: "));
      Serial.println(number);
    }
  }
  Serial.flush();
  Serial.end();
  rowsAsInputs();
}

// Empty the number being typed.
void clearNumber() {
  length = 0;
  number[0] = '\0';
}

// Set up the pins and displays, and show the initial state.
void setup() {
  rowsAsInputs();
  for (uint8_t c = 0; c < COLS; ++c) pinMode(COL_PINS[c], INPUT);
  clearNumber();
  report(0);
}

// Poll the keypad and keep the flashing cursor going, without blocking.
void loop() {
  char key = scanKeypad();
  if (!key) return;

  delay(DEBOUNCE_MS);
  if (scanKeypad() != key) return;

  if (key == '*') {
    clearNumber();
    report(key);
  } else if (key == '#') {
    report(key);
    clearNumber();
  } else if (key >= 'A') {
    report(key);              // A-D: show only
  } else {
    if (length < MAX_DIGITS) {
      number[length++] = key;
      number[length] = '\0';
    }
    report(key);
  }

  // Wait for release so one press is reported once.
  do {
    while (scanKeypad()) delay(5);
    delay(DEBOUNCE_MS);
  } while (scanKeypad());
}
