I am trying to debounce some buttons using some code that was recommended, the issues is that the ports need to be defined in an array. I have done some reading on the internet but to no avail. Jack state to remember to " initialize State and Index to zero" and I'm unsure how to accomplish this
Figure 3 shows one approach. DebounceSwitch(), which is called regularly by a
timer tick, reads an entire byte-wide port that contains up to 8 individual switches. On
each call it stuffs the port’s data into an entry in circular queue State. Though shown as
an array with but a single dimension, a second loiters hidden in the width of the byte.
State consists of columns (array entries) and rows (each defined by bit position in an
individual entry, and corresponding to a particular switch).
A short loop ANDs all column entries of the array. The resulting byte has a one in each
bit position where that particular switch was on for every entry in State. After the loop
completes, variable j contains 8 debounced switch values.
One could exclusive OR this with the last Debounced_State to get a one in each bit
where the corresponding switch has changed from a zero to a one, in a nice debounced
fashion.
Don’t forget to initialize State and Index to zero.
- Code: Select all
int State[]={PORTCbits.RC0,PORTDbits.RD0};
char Index=0;
char counter=0;
#define MAX_CHECKS 10
uint8_t Debounce_State;
uint8_t State[MAX_CHECKS];
uint8_t Index;
void DebounceSwitch()
{
uint8_t i,j
State[Index]=RawKeyPressed();
++Index;
j=0xff;
for(i=0; i<MAX_CHECKS;i++)j+j & State[i];
Debounce_State= j;
if(Index>=MAX_CHECKS)Index=0;
}
void main(void) {
// Initialize the device
SYSTEM_Initialize();
while (1)
{
while (!TMR1IF);
TMR1_Reload();
counter++;
if (counter ==5)
{
DebounceSwitch();
counter =0;
}
TMR1IF = 0;
}
}