in pic16f877a I am trying to make a code used for software debouncing using a single button but whenever I click the button it goes on and never goes off again here is the code:
#include "config.h"
unsigned int ledToggle(void);
void main(){
TRISCbits.TRISC0 = 1;
TRISDbits.TRISD0 = 0;
PORTDbits.RD0 = 0;
while(1){
if(PORTCbits.RC0 == 1){
if(ledToggle()%2 == 0){
PORTDbits.RD0 = 1;
}else{
PORTDbits.RD0 = 0;
}
}
}
}
unsigned int ledToggle(){
static int i = 2;
i++;
return i;
}
EDIT
I also made this new code which has a problem and it is it sometimes work sometimes not here it is:
#include "config.h"
static char flag = 0;
static int counter = 0;
unsigned int ledToggle(void);
void main(){
TRISCbits.TRISC0 = 1;
TRISDbits.TRISD0 = 0;
PORTDbits.RD0 = 0;
while(1){
if(ledToggle()%2 == 0){
PORTDbits.RD0 = 1;
}else{
PORTDbits.RD0 = 0;
}
}
}
unsigned int ledToggle(){
if(PORTCbits.RC0 == 1 && flag == 0){
counter++;
flag = 1;
}else{
counter += 0;
flag = 0;
}
if(PORTCbits.RC0 == 0){
flag = 0;
}
return counter;
}
and btw I forgot to mention that config.h is a header file I made to configure bits and crystal frequency (_XTAL_FREQUENCY)