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);
}