While figuring out buttons I found this code on these forums. It's quite easy to follow and demonstrates state changes.
State changes are what you really want to keep track of. What most people call a button press is really a press and release.
/*
* Sample sketch to show how to detect the state changes of a momentary switch (button).
* Debounce is also implemented without the use of delay and the length that the button
* is pushed down for is printed to the serial monitor.
*/
const int buttonPin = 2;
const unsigned long debounceInterval = 20; // Increase until bouncing stops
unsigned long debounceTime = 0;
unsigned long buttonPushedDownTime = 0;
int lastReading = HIGH;
int lastState = HIGH;
int currentState = HIGH;
void setup()
{
pinMode(buttonPin, INPUT_PULLUP);
Serial.begin(115200);
Serial.println("[start]");
}
void loop()
{
unsigned long currentTime = millis();// Store the current time in a variable for easy access
unsigned long lengthButtonWasDown = 0;// This variable will be used to store the length of time that the button was depressed for
int currentReading = digitalRead(buttonPin);// Start by getting the current reading from our button
if (currentReading != lastReading) debounceTime = currentTime; // If it's different than our last reading, reset the debounce timer
if (currentTime - debounceTime > debounceInterval) currentState = currentReading; // If the button has stayed at the same reading for long enough, update the button's state
// At this point, the debounce is taken care of, we just need to look for the signal edges
// of the button. That is, when the button goes from LOW to HIGH or HIGH to LOW.
if (currentState != lastState)
{
// First we check if this which transistion we have. If the button is pushed down, then
// the currentState will be LOW. Otherwise, the button is being released.
if (currentState == LOW)
{
Serial.println("Button pushed down");
buttonPushedDownTime = currentTime;
}
else
{
// Calulate how long it was pushed down
lengthButtonWasDown = currentTime - buttonPushedDownTime;
// Print the results to the Serial monitor
Serial.print("Button realeased after ");
Serial.print(lengthButtonWasDown);
Serial.print(" seconds");
}
}
// Update the "last" variables
lastReading = currentReading;
lastState = currentState;
}