c++raspberry-piwiringpi

Multiple function calls on one interrupt-generating button press


So I have a c++ program here utilizing wiringPi to sleep a thread until a button press (on a rapsberryPi using the GPIO), but when the button is pressed it can often print the message multiple times. I tried to remedy this by sleeping for a few seconds within the loop but this didn't help leading me to believe that it has something to do with how the interrupt generation calls the function. Any advice for how I can solve this so the function is only ran once per button press?

#include <stdlib.h>
#include <iostream>
#include <wiringPi.h>
#include <unistd.h>

void printMessage(void) { 
    std::cout << "Button pressed! hooray" << std::endl; 
}

int main(int argc, char const *argv[]) {   

    wiringPiSetup();

    while(true) {
        wiringPiISR(3, INT_EDGE_FALLING, &printMessage);//3 is the wiringPi pin #
        sleep(3);
    }

}

Solution

  • I think you only have to set the ISR once (call wiringPiISR once). After that just sleep forever (while(1)sleep(10);). You seem to have debounced your button using a print statement. Debouncing can often be a matter of timing, and printing takes a few microseconds causing the button to be "sort of" debounced. It can however still do some bouncing

    For more debouncing info see this SO page