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;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s