Matrix Keypad - Optimisation

robtillaart said:

Another point of attention is that in readkeyboard you test keyboard value even if keypressed has gotten a value. Replace all the if's with multiple nested if else .. Here a snippet of code how that could be done.

  keyboardValue = analogRead(keyboardPin); // read the value (0-1023)

if (keyboardValue < 68){keypressed = 1};
 else if (keyboardValue < 108)) {keypressed = 2};
 else if (keyboardValue < 153)) {keypressed = 3};
 else if (keyboardValue < 186)) {keypressed = 4};
 else if .... etc




The tests are simpler and the number of tests are less. This is caused by the fact that we use earlier tested information. If a value is not smaller than 68 it must be greater or equal so we do not need to test that.

would that work like that or would I need to start a the high end and work my way down

ie

keyboardValue = analogRead(keyboardPin); // read the value (0-1023)
  if (keyboardValue > 970){keypressed = 16;}
  else if (keyboardValue > 945)) {keypressed = 15;}
  else if (keyboardValue > 898)) {keypressed = 14;}
  else if (keyboardValue > 854)) {keypressed = 13;}
  ...
  else if (keyboard value > 24) {keypressed = 1;}

that way in the case where no key is pressed is represented by nothing happening and it will just loop around and scan the value again and evaluate it against the multiple nested if else statements until it is above 24

another thing that concerns me with the code is

  Serial.println(k);                // print the value back to the Serial view window on your PC
  delay(1000);

the delay seems long. won't it take a second between each keypress? or is that so it doesn't put out multiple digits for the same key press? am I misunderstanding the function of the delay there?

one final question, in the code you sent, don't I need to initialize all the new variables you mention

int k = 0;
int kbvalue = 0;
int kbv = 0;

Thanks again,

Carl