Skip to content

Instantly share code, notes, and snippets.

@cmoz
Created March 23, 2022 14:21
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 cmoz/3702bd077fe42f7ba7e8837e6c3b603d to your computer and use it in GitHub Desktop.
Save cmoz/3702bd077fe42f7ba7e8837e6c3b603d to your computer and use it in GitHub Desktop.
/*
* Created by ArduinoGetStarted.com
*
* This example code is in the public domain
*
* Tutorial page: https://arduinogetstarted.com/tutorials/arduino-button-long-press-short-press
*/
// constants won't change. They're used here to set pin numbers:
const int BUTTON_PIN = 7; // the number of the pushbutton pin
const int SHORT_PRESS_TIME = 500; // 500 milliseconds
// Variables will change:
int lastState = LOW; // the previous state from the input pin
int currentState; // the current reading from the input pin
unsigned long pressedTime = 0;
unsigned long releasedTime = 0;
void setup() {
Serial.begin(9600);
pinMode(BUTTON_PIN, INPUT_PULLUP);
}
void loop() {
// read the state of the switch/button:
currentState = digitalRead(BUTTON_PIN);
if(lastState == HIGH && currentState == LOW) // button is pressed
pressedTime = millis();
else if(lastState == LOW && currentState == HIGH) { // button is released
releasedTime = millis();
long pressDuration = releasedTime - pressedTime;
if( pressDuration < SHORT_PRESS_TIME )
Serial.println("A short press is detected");
}
// save the the last state
lastState = currentState;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment