2

I have a simple sketch with a button that triggers an interruption set to happen when the button pin goes from HIGH to LOW. It has debouncing so no repetitions happen when the button is pressed, but sometimes when releasing the button the interruption also fires. Why would that be? Shouldn't the debouncing take care of any micro-rising during the release of the button?

volatile int contador = 0;
int n = contador;

long t = 0;
void setup() {    

    pinMode(2, INPUT_PULLUP);
    attachInterrupt( 0, incrementaContador, FALLING);
} 

void loop() {   
    if (n != contador) {
        n = contador;
    }
}

void incrementaContador() {

    if ( millis() > (t + 50) ) {
        contador++ ;
        t = millis();
    }
}

This same code works correctly when set to LOW instead of FALLING.

5
  • 2
    Shouldn't the debouncing take care of any micro-rising during the release of the button? - That depends on the debouncing. Schematic please?
    – Majenko
    May 18, 2017 at 9:44
  • Also if you think that "if" in your ISR is good debouncing you're sorely mistaken.
    – Majenko
    May 18, 2017 at 9:45
  • 1
    Think about what happens. You press the button, and the ISR triggers on each bounce. It counts once because all the bouncing happens within 50ms. Then, say 100ms later, you release the button. Again bouncing happens, and the ISR triggers on each bounce, and one of them within a 50ms window gets counted. You have no distinction between rising bounce and falling bounce. It's all up-down-up-down-up. The real thing you should be looking for is the final position that hasn't changed for a while.
    – Majenko
    May 18, 2017 at 9:49
  • Thank you for the reply @Majenko. The schematic is just a button attached to pin 2 and ground. I forgot to mention that this code works perfectly when the interruption is set to trigger on LOW instead of FALLING. I checked to see if incrementing the delay in the ISR would help and with 500ms it debounces also the releasing of the button. But why the difference between the two modes. Does FALLING also trigger when 0v is not reached?
    – romanoma
    May 18, 2017 at 14:41
  • This question seems to have been abandoned.
    – Nick Gammon
    Aug 15, 2018 at 8:09

1 Answer 1

2

but sometimes when releasing the button the interruption also fires

Yes, well when you release the button it may also bounce. In other words OFF/ON/OFF so that will count as a press. A capacitor over the switch might be better.

Example:

Hardware debounce

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.