It's my custom debounce code
It keeps the led on by flipping the required threshold value when triggered after the led has turned on to keep the led in a high state and vice verse triggered again, the comments on the code explain it in more detail.
/*
* This code is my custom debounce code, I made this but this isn't working as planned,
* see the thing is that it turns on when I hold the button and if I release it,
* it starts to flickers and then gradually turn off, what is wrong with my code ?
* I can't see it.
*/
const int ledPin = 13; // led connected to pin 13
const int PushButton = 2; // a pushbutton connected to pin 2
int switcher = HIGH; // the switcher changes it's value, we require this later
int dilay = 1; // controls the delay
unsigned long lastTrigger = 0; // records the last time the led was turned on
void setup() {
pinMode(ledPin, OUTPUT); // sets ledpin as output
pinMode(PushButton, INPUT); // sets pushbutton pin as input
}
void loop() {
int pushButtonState = digitalRead(PushButton); // stores the value of the pin each time the loop begins agian
if((millis() - lastTrigger) >= dilay){ // my custom debounce code
if(pushButtonState == switcher){ // this is the trick, when the pushbutton pin is high it's equal to the switcher value
digitalWrite(ledPin, HIGH); // it turns on the led
int switcher = LOW; // now the switcher value will be low now the pushbutton pin value will also be low keeping the led on
}else{
digitalWrite(ledPin, LOW); // now if the led is on and pushbutton is high, then it will not be equal to the switcher because we had changed it in the previous statement
int switcher = HIGH; // now the switcher is high and the pushbutton value low, switcher isn't equal to pushbutton so there by keeping the ledpin as low
}
if(pushButtonState == 1){ // if pushbutton is high
int lastTrigger = millis(); // then lastTrigger equals to the current time
}
}
}