/*

Demostration of an external hardware interrupt attached to a button  which
also a debouncing mechanism which should keep the increments to 1 per press
but more are still possible depending on how quickly you press the button
repeatedly (I got 4 - 5 sometimes).

*/


#include <Debouncer.h>

const int buttonPin = 2;   // Pin for the button
volatile int buttonPresses = 0; // Count button presses
volatile int prevPresses = 0;
const int debounceDelay = 200;

volatile bool buttonPressed = false;
unsigned long lastDebounceTime = 0;



void setup() {
  pinMode(buttonPin, INPUT); // Set button pin as input with internal pull-up
  attachInterrupt(digitalPinToInterrupt(buttonPin), countPresses, FALLING); // Attach interrupt
  Serial.begin(9600); // Start serial communication
  noInterrupts();
}

void loop() {
  
  if(buttonPresses != prevPresses) {
  Serial.println(buttonPresses); // Print the count of button presses
  prevPresses = buttonPresses;
  }
  
  delay(1000); // Wait for a second
}

void countPresses() {
  unsigned long currentTime = millis();
  if ((currentTime - lastDebounceTime) > debounceDelay) {
  lastDebounceTime = currentTime;
  buttonPressed = true;
  buttonPresses++; // Increment the button press counter
  
} }