Switch debouncing

For a comprehensive introduction to the need for switch debouncing in microprocessor applications and approaches to doing so. Take a look at this excellent guide by The Ganssle Group.

A simple software debounce routine for debouncing the press of an active low switch, such as a momentary push switch directly attached from the input pin (with pullups enabled) of the microcontroller down to ground, is shown below. In this case the switch is attached to pin0 on port B.

char debounce(void)
{
static char count=0;
if (PINB & (1<<PB0)) count=0;
else count++;
if (count > 10) return 1;
else return 0;
}

This code simply implements a counter that requires the pin to be in the logic zero state for 10 successive samples, before returning a one. The count can be increased or decreased as necessary to ensure robust operation of the switch. Software debouncing can also be realised in an more efficient form by simply using a char variable and a logical shift left to count the successive samples. In this implementation the maximum count is 8.

char debounce(void)
{
static char state=0xFF;
state=(state << 1)|(PINB & (1 << PB0));
if state==0 return 1;
else return 0;
}

Leave a comment