const int buttonPin = 2; // Button pin
int lastButtonState = HIGH; // Previous button state
int risingEdges = 0;
int fallingEdges = 0;
unsigned long lastDebounceTime = 0;
const unsigned long debounceDelay = 50; // Debounce time (ms)
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT_PULLUP); // Enable internal pull-up resistor
}
void loop() {
int currentButtonState = digitalRead(buttonPin);
unsigned long currentTime = millis();
// Check if button state changed and debounce it
if (currentButtonState != lastButtonState) {
lastDebounceTime = currentTime; // Reset debounce timer
}
if ((currentTime - lastDebounceTime) > debounceDelay) {
// Only count edges when a stable state change is detected
if (currentButtonState != lastButtonState) {
if (currentButtonState == LOW) {
risingEdges++;
} else {
fallingEdges++;
}
}
lastButtonState = currentButtonState; // Update button state
}
// Print results
Serial.print("Rising Edges: ");
Serial.print(risingEdges);
Serial.print(" | Falling Edges: ");
Serial.println(fallingEdges);
delay(1000); // Small delay to reduce serial flooding
}