/*
 *  Analog Key
 */

const int pin = A1;   // Define Analog Pin:
const int keys = 16;  // Number of keys on keypad
const int border = 5; // Border between keys
int keyValue = 0;     // Variable to store button being pressed:
char key;             // Key 

//const char buttonIDs[keys] = {'1', '2', '3', 'A', '4', '5', '6', 'B', '7', '8', '9', 'C', '*', '0', '#', 'D'}; // Button names
const char buttonIDs[keys] = { 'D', '#', '0', '*', 'C', '9', '8', '7', 'B', '6', '5', '4', 'A', '3', '2', '1'};
int keyValues[keys]       = {1023, 815, 677, 579, 512, 454, 407, 370, 341, 314, 291, 272, 256, 240, 227, 215}; // Analog values that correspond to each button:
int thresholds[keys-1]    = {      919, 746, 628, 545, 483, 431, 389, 355, 328, 303, 282, 264, 248, 234, 221};

// Gemessen: 1022 814 676 578 511 452 406 368 339 312 289 270 254 238 225 213 (1)
// Tasten:   1023 815 677 579 512 454 407 370 341 314 291 272 256 240 227 215
// Mitte:      -  919 746 628 545 483 431 389 355 328 303 282 264 248 234 221

void setup() {
  Serial.begin(115200);
  delay(500); // wait of Serial Monitor
  Serial.println("\nAnalog-out Keypad Test");
}

char readKey() { 
  if(analogRead(pin) > 100) while(analogRead(pin) > 100); // wait until key is released
  do {
    keyValue = analogRead(pin);
  } while (keyValue < 200);    // wait until key is pressed
  Serial.print("\tKeyvalue is "); Serial.println(keyValue);


  for (int i = 0; i< keys; i++) {
    if ((keyValue > keyValues[i] - border) && (keyValue < keyValues[i] + border)) return buttonIDs[i];
  }
  return 'Z';  // illegal
}


void loop() {
  Serial.print("Press any key: "); 
  key = readKey(); 
  Serial.print("You pressed: "); Serial.println(key);
}
