// Matrix keypad *******************************************************
const int Matrix = A2;
const int SmallestGap = 24;
int AnalogVals[] = {1023, 728, 693, 657, 632, 605, 567, 541, 517, 477, 439,
404, 371, 316, 290, 264, 220, 186, 151, 93, 0, -100};
int Buttons[] = {-1, 1, 2, 3, 10, 17, 4, 7, 14, 5, 8,
0, 6, 9, 11, 15, 12, 18, 13, 19, 20};
// Returns the keypad character or -1 if no button pressed
int ReadKeypad() {
int val, lastval=0, count = 0;
do {
val = analogRead(Matrix);
if (abs(val-lastval)<2) count++;
else { lastval = val; count = 0; }
} while (count <3);
int i = 0;
val = val - SmallestGap/2;
while (val < AnalogVals[i]) { i++; }
return Buttons[i - 1];
}