Scanning Keypad

Trying to get a key long press whenever it is done, without using interrupt

void checkKeys(){
  if (keypad.getKeys()) // check for keypad activity
    // we won't handle multiple keypresses, just single ones, so just key index 0
    const byte key = keypad.key[0].kchar;
    const byte state = keypad.key[0].kstate; // IDLE, PRESSED, HOLD, RELEASED

    switch (key) {

      case '#': {
          static unsigned long pressedTime; // static so the value is remembered like a global
          if (state == PRESSED) {
            pressedTime = millis();
          } else if (state == RELEASED) {
            if (millis() - pressedTime > LongPress) {
        } break;

void send(){
  lcd.print("Values of ");
  lcd.print(" sent");
void loop(){
  // put your main code here, to run repeatedly:

it works fine when it's the only method in void loop, i.e. checkKeys() , but when other methods, read_sensors() checkSD() log() lcd_display() , it doesn't work anymore.

Please read the first topic telling how to use this forum.
Post the entire code, autoformatted in the IDE, then using code tags, </>, when pasting.
Post the wiring diagram.

Then the problem must be in the other code which you did not post.

My guess is that your other functions are blocking functions (they halt and wait for something)...

I suspect that the other operations are taking long enough that by the time you get back to check the keyboard, TWO buttons have changed state. One is no longer pressed and another is pressed. They would appear in the event list as one key going RELEASED or IDLE and the other going PRESSED or HELD.

I think it will be fixed if you look at all of the entries in the list of key events you asked for.

You might be able to use the "HELD" state for your long-press. You can use the keypad.setHoldTime() to set the time for a long-press (milliseconds up to 30,000).

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.