button pressed more than 2 seconds do somethingelse

It is fairly involved, :).

The basic logic is to count the time the key has been pressed. If it exceeds a preset limit, test for long presses.

Here is the basic flow:

#define KEY_PRESSED LOW //state of key being pressed
#define KEY_NO_PRESS 0 //key not pressed
#define KEY_SHORT_PRESS 1 //key pressed short
#define KEY_LONG_PRESS 2 //key pressed long
#define KEY_DURATION 100 //cycle count, minimum threshold to test for long presses

unsigned char key_read(unsigned char pin)  {
  unsigned char count=0;
  if (digitalRead(pin) != KEY_PRESSED) return KEY_NO_PRESS; //key not pressed
  //key is pressed
  while (digitalRead(pin) == KEY_PRESSED) count+=1; //increment count if key is continuously pressed
  if (count > KEY_DURATION) return KEY_LONG_PRESS;
  else return KEY_SHORT_PRESS;
}

The test for long_press / short_press could be further enhanced, based on your design.

1 Like