Making a Library for Push Buttons and Software Debouncing

Making a Library for Push Buttons and Software Debouncing

The Button Press Library:

#ifndef ButtonPress
#define ButtonPress

include

char ButtonPressed(int buttonNumber, unsigned char pinOfButton, unsigned char portBit, int confidenceLevel);

char Pressed[numberOfButtons];
int Pressed_Confidence_Level[numberOfButtons]; //Measure button press cofidence
int Released_Confidence_Level[numberOfButtons]; //Measure button release confidence

char ButtonPressed(int buttonNumber, unsigned char pinOfButton, unsigned char portBit, int confidenceLevel)
{
if (bit_is_clear(pinOfButton, portBit))
{
Pressed_Confidence_Level[buttonNumber] ++; //Increase Pressed Conficence
Released_Confidence_Level[buttonNumber] = 0; //Reset released button confidence since there is a button press
if (Pressed_Confidence_Level[buttonNumber] > confidenceLevel) //Indicator of good button press
{
if (Pressed[buttonNumber] == 0)
{
Pressed[buttonNumber] = 1;
return 1;
}
//Zero it so a new pressed condition can be evaluated
Pressed_Confidence_Level[buttonNumber] = 0;
}
}
else
{
Released_Confidence_Level[buttonNumber] ++; //This works just like the pressed
Pressed_Confidence_Level[buttonNumber] = 0; //Reset pressed button confidence since the button is released
if (Released_Confidence_Level[buttonNumber] > confidenceLevel)
{
Pressed[buttonNumber] = 0;
Released_Confidence_Level[buttonNumber] = 0;
}
}
return 0;
}

#endif

This is the program that contains all of the code that determines the button state and keeps track of the confidence levels for the button press and release for eliminating the debouncing effect. This library file is named: "ButtonPress.h" which you can see in the include file of the main program. If you copy and paste this code and save it as another name, you will need to change the include file for the main program.

The Actual Program that we Would Write Using the Button Press Library

#define numberOfButtons 2

include
#include"ButtonPress.h"

int main(void)
{
DDRB = 0b00001100;
PORTB = (1 << PINB0)|(1 << PINB1);

while (1)
{
if (ButtonPressed(0, PINB, 0, 100)) PORTB ^= (1 << PINB2);

if (ButtonPressed(1, PINB, 1, 100)) PORTB ^= (1 << PINB3);
}
}

Notice how short the main program is now. Most of the code for the button presses and software debouncing is abstracted out in a library. All you need to do is include the ButtonPress.h file and use a define statement at the beginning of the program to inform the compiler how many buttons you wish to use. To determine if a button is pressed, just make an "if" statement with the information relating to the specific button like the button number, the pin and port and the threshold of theconfident level for the software debouncing.

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.