Skip to content

Instantly share code, notes, and snippets.

@battis
Created February 1, 2018 19:17
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 battis/38e8ed027a1c6792c47601bba2586d99 to your computer and use it in GitHub Desktop.
Save battis/38e8ed027a1c6792c47601bba2586d99 to your computer and use it in GitHub Desktop.
Button Timing
int buttonPin = 2;
int buttonState;
unsigned long timestamp;
void setup() {
// prepare ports for communication
pinMode(buttonPin, INPUT);
Serial.begin(9600);
// set initial timer and button state values
timestamp = millis();
buttonState = digitalRead(buttonPin);
}
void loop() {
// if the button's state changed (pressed -> released or released -> pressed)
if (digitalRead(buttonPin) != buttonState) {
// if the button _was_ being pressed before...
if (buttonState == LOW) {
// print out timing (note that we have to convert the numeric expression to a String for this to work
Serial.print("Button was pressed for " + String(millis() - timestamp) + " milliseconds\n");
// flip state to opposite (released)
buttonState = HIGH;
// ...otherwise, the button _was_ released before
} else {
Serial.print("Button was released for " + String(millis() - timestamp) + " milliseconds\n");
buttonState = LOW;
}
// reset the timer for the new state
timestamp = millis();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment