The following function polls the button at nominally 1 millisecond intervals and required that the state remain "releases" to 20 consecutive polls. That will typically be sufficient to debounce most switches while retaining responsiveness.
Replace your while(bcm2835_gpio_lev(PIN)){}
loop with a call to waitButtonRelease()
.
#include <unistd.h>
#define DEBOUNCE_MILLISEC 20
void waitButtonRelease()
{
int debounce = 0 ;
while( debounce < DEBOUNCE_MILLISEC )
{
usleep(1000) ;
if( bcm2835_gpio_lev(PIN) )
{
debounce = 0 ;
}
else
{
debounce++ ;
}
}
}
You may find it necessary also to debounce button presses as well as releases. That is done in the same way, but counting the opposite state:
void waitButtonPress()
{
int debounce = 0 ;
while( debounce < DEBOUNCE_MILLISEC )
{
usleep(1000) ;
if( !bcm2835_gpio_lev(PIN) )
{
debounce = 0 ;
}
else
{
debounce++ ;
}
}
}
Or perhaps a single function to debounce either state:
#include <stdbool.h>
void waitButton( bool state )
{
int debounce = 0 ;
while( debounce < DEBOUNCE_MILLISEC )
{
usleep(1000) ;
if( bcm2835_gpio_lev(PIN) == state )
{
debounce++ ;
}
else
{
debounce = 0 ;
}
}
}
Given this last function, your main while loop might look like:
while(1)
{
waitButton( true )
printf("The button has been pressed\n");
waitButton( false ) ;
}
If you have access to a digital storage oscilloscope, you might probe the switch signal directly to see exactly what the switch bounce looks like. It may help you understand the problem and also to tailor the debounce to the characteristics of your particular switch.