volatile uint32_t count = 0; // Holds the count of interrupts
uint32_t lastReportedCount = 0; // Holds the last count that was reported
// Variables for debouncing
unsigned long lastDebounceTime = 0; // Last time button was pressed
unsigned long debounceDelay = 50; // Debounce delay in milliseconds
// Function to increment the count
void incrementCount() {
unsigned long currentTime = millis();
if (currentTime - lastDebounceTime > debounceDelay) {
count++;
lastDebounceTime = currentTime; // Update debounce time
}
}
// Function to decrement the count
void decrementCount() {
unsigned long currentTime = millis();
if (currentTime - lastDebounceTime > debounceDelay) {
if (count > 0) {
count--;
}
lastDebounceTime = currentTime; // Update debounce time
}
}
void setup() {
Serial.begin(115200);
pinMode(2, INPUT_PULLUP); // Set pin 2 as input with pull-up resistor (for increment)
pinMode(4, INPUT_PULLUP); // Set pin 3 as input with pull-up resistor (for decrement)
// Attach interrupts to both buttons with a debounce mechanism
attachInterrupt(digitalPinToInterrupt(2), incrementCount, CHANGE); // Increment on state change
attachInterrupt(digitalPinToInterrupt(4), decrementCount, CHANGE); // Decrement on state change
// Interrupt on falling edge for button 2
}
void loop() {
// Only report the count if it has increased or decreased
noInterrupts();
if (count != lastReportedCount) {
lastReportedCount = count; // Update the last reported count
Serial.print("Interrupt count: ");
Serial.println(count); // Print the current count
}
interrupts();
// Small delay for debounce
delay(100); // Add a small delay to prevent excessive reporting
}