Short and long button push code from instructables.

Hi, I found this code on an instructables page (http://www.instructables.com/id/Arduino-Button-Tutorial/)(step 4). I have the setup working, although using a Nano instead of an Uno. I never seem to get a long push. Using the serial monitor i can see i'm getting a non-press and a Short-press, but never long. Is there something in the code causing this? I have tried asking on the originators page but no response. Cheers for any guidance.

#define BUTTON_PIN        2  // Button

#define LONGPRESS_LEN    25  // Min nr of loops for a long press
#define DELAY            20  // Delay per loop in ms

enum { EV_NONE=0, EV_SHORTPRESS, EV_LONGPRESS };

boolean button_was_pressed; // previous state
int button_pressed_counter; // press running duration

void setup()
{
  pinMode(BUTTON_PIN, INPUT);
  digitalWrite(BUTTON_PIN, HIGH); // pull-up
  Serial.begin(9600);
  button_was_pressed = false;
  button_pressed_counter = 0;
}

int handle_button()
{
  int event;
  int button_now_pressed = !digitalRead(BUTTON_PIN); // pin low -> pressed

  if (!button_now_pressed && button_was_pressed) {
    if (button_pressed_counter < LONGPRESS_LEN)
      event = EV_SHORTPRESS;
    else
      event = EV_LONGPRESS;
  }
  else
    event = EV_NONE;

  if (button_now_pressed)
    ++button_pressed_counter;
  else
    button_pressed_counter = 0;

  button_was_pressed = button_now_pressed;
  return event;
}

void loop()
{
  // handle button
  boolean event = handle_button();

  // do other things
  switch (event) {
    case EV_NONE:
      Serial.print(".");
      break;
    case EV_SHORTPRESS:
      Serial.print("S");
      break;
    case EV_LONGPRESS:
      Serial.print("L");
      break;
  }

  // add newline sometimes
  static int counter = 0;
  if ((++counter & 0x3f) == 0)
    Serial.println();

  delay(DELAY);
}

That solution you have found is not very elegant. It uses a counter and a series of delay() calls. That is bad if you want your sketch to do anything apart from monitor the button else because the delay blocks everything.

Usually you use millis() to record the time of the button press. When the button is released, you again use millis() and calculate the elapsed time for which the button was held in.

Edit:

boolean event = handle_button();

Try an int instead of a boolean.

There is a neat way to do different button click types in this link

...R

Robin2:
There is a neat way to do different button click types in this link

...R

That works brilliantly! Thanks for the assist, Robin2 :smiley: