Generating interrupts with buttons

Hi all,

I've been playing with a basic interrupt example, connecting two buttons to PIN2 and PIN3 respectively. Using the code below the wrong interrupt sometimes fires when I put a capacitor across each button (pressing the button connected to PIN2 fires the interrupt associated with PIN3, and vice versa). In fact, I has hoping to avoid the "if (thisItr - lastItr > ITR_DELAY)" checks altogether by adding the capacitors.

Any suggestions for how to do this properly would be appreciated!

#define PIN_LED 13

#define ITR_DELAY 200

int ledState = LOW;

int itrCountAccept0 = 0;
int itrCountIgnore0 = 0;
int itrCountAccept1 = 0;
int itrCountIgnore1 = 0;

unsigned long lastItr = 0;
unsigned long thisItr = 0;

void setup() {
  pinMode(PIN_LED, OUTPUT);
  attachInterrupt(0, itr0, RISING);
  attachInterrupt(1, itr1, RISING);
  Serial.begin(9600);
}

void itr0() {
  thisItr = millis();
  if (thisItr - lastItr > ITR_DELAY) {
    lastItr = thisItr;
    itrCountAccept0++;
      
    ledState = !ledState;
  }
  else {
    itrCountIgnore0++;
  }
}

void itr1() {
  thisItr = millis();
  if (thisItr - lastItr > ITR_DELAY) {
    lastItr = thisItr;
    itrCountAccept1++;
      
    ledState = !ledState;
  } 
  else {
    itrCountIgnore1++;
  }
}

int count = 0;
void loop() {
  digitalWrite(PIN_LED, ledState);
  delay(100);
  count++;
  
  if (0 == count % 5) {
    Serial.print(itrCountAccept0);
    Serial.print("  ");
    Serial.print(itrCountIgnore0);
    Serial.print("    ");
    Serial.print(itrCountAccept1);
    Serial.print("  ");
    Serial.println(itrCountIgnore1);
  }
}

There certainly shouldn't be a capacitor directly across the button, that'll generate a
large current spike when the button closes, inducing voltages in all nearby wires and damaging the button contacts.

Are you trying to add a low-pass filter to the button perchance?

Hi MarkT, thank you for your reply. The capacitors are across the resistors, not the buttons - sorry for the typo.

You should not use interrupts if buttons aren't debounced.

Hi kustom, thank you for replying. Do you mean debounced in software or in hardware? I was aiming for the latter but so far I could not get rid of the software checks.

mortendahl:
Hi kustom, thank you for replying. Do you mean debounced in software or in hardware? I was aiming for the latter but so far I could not get rid of the software checks.

In software. That is, use interrupts only if you got rid of bouncing via hardware. There is an excellent video explaining hardware debouncing here: Tutorial 10 for Arduino: Interrupts and Hardware Debouncing - YouTube

Thank you, kustom, looks like a perfect match for what I need.

Out of curiosity, do you have any explanation for why the wrong interrupt can be triggered when there’s a capacitor across the resistor (as in the simple filter circuit here: Switch Contact Debouncing)?