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
}
}
}
-
1how is the button wired? do you have a pulldown resistor?Juraj– Juraj ♦2018年09月28日 18:11:00 +00:00Commented Sep 28, 2018 at 18:11
-
the button is a switch which connects the 5v pin and pin 2, and no i don't use a pull down resistorSanjay .S Kumar– Sanjay .S Kumar2018年10月02日 06:56:02 +00:00Commented Oct 2, 2018 at 6:56
-
without pulldown, the pin free floats between LOW and HIGH when disconnected from 5VJuraj– Juraj ♦2018年10月02日 07:04:18 +00:00Commented Oct 2, 2018 at 7:04
1 Answer 1
Change int switcher = LOW/HIGH
to just switcher = LOW/HIGH
.
Otherwise you are redefining the variable, and will make it a local variable, and not change the global variable with the same name (as you are expecting).
-
1PS you code isn't actually doing any debouncing. It negates it a bit by only polling the input pin every 1 ms. But in some switches bouncing can take up to 6ms.Gerben– Gerben2018年09月28日 18:21:03 +00:00Commented Sep 28, 2018 at 18:21
-
now with the change you suggested, it makes the led blink nowSanjay .S Kumar– Sanjay .S Kumar2018年10月02日 07:02:00 +00:00Commented Oct 2, 2018 at 7:02