Skip to content

Instantly share code, notes, and snippets.

@xoan
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xoan/588b121f900e9e1774a3 to your computer and use it in GitHub Desktop.
Save xoan/588b121f900e9e1774a3 to your computer and use it in GitHub Desktop.
Handle short/long press and release events on a digital button
/*
Button.ino
Handle short/long press and release events on a digital button
Based on Arduino Button Tutorial
http://www.instructables.com/id/Arduino-Button-Tutorial
*/
#define BUTTON_PIN 12
#define SHORTPRESS_MILLIS 50
#define LONGPRESS_MILLIS 1000
bool button_was_pressed;
bool button_was_short_pressed;
bool button_was_long_pressed;
// store millis when button is pressed
long previous_millis;
// store action to be executed when button is released
short action;
enum { NONE = 0, PRESS, SHORTPRESS, LONGPRESS, RELEASE };
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP);
Serial.begin(9600);
// button states
button_was_pressed = false;
button_was_short_pressed = false;
button_was_long_pressed = false;
previous_millis = 0;
}
int read_button() {
int event;
unsigned long current_millis = millis();
// button is pressed when pin is read as low
int button_now_pressed = !digitalRead(BUTTON_PIN);
if (button_now_pressed) {
if (!button_was_short_pressed && current_millis - previous_millis > SHORTPRESS_MILLIS) {
event = action = SHORTPRESS;
// change button short pressed state
button_was_short_pressed = true;
} else if (!button_was_long_pressed && current_millis - previous_millis > LONGPRESS_MILLIS) {
event = action = LONGPRESS;
// change button long pressed state
button_was_long_pressed = true;
} else {
event = PRESS;
// change button pressed state
button_was_pressed = true;
}
} else {
if (button_was_pressed) {
event = RELEASE;
// reset button states
button_was_pressed = false;
button_was_short_pressed = false;
button_was_long_pressed = false;
} else {
event = action = NONE;
}
// reset millis
previous_millis = current_millis;
}
return event;
}
void loop() {
int event = read_button();
switch (event) {
case NONE:
Serial.print(":");
break;
case PRESS:
Serial.print(".");
break;
case SHORTPRESS:
Serial.print("S");
break;
case LONGPRESS:
Serial.print("L");
break;
case RELEASE:
switch (action) {
case NONE:
Serial.print("N");
break;
case SHORTPRESS:
Serial.print("S");
break;
case LONGPRESS:
Serial.print("L");
break;
}
break;
}
// add newline sometimes
static int counter = 0;
if ((++counter & 0x3f) == 0)
Serial.println();
delay(10);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment