I tried to build a blink LED and doing debounce with delay() for the time between lights was frustrating because it nothing is processed during the delay time, which means that debounce can only be checked at a certain period. I wrote a function using millis() to replace delay() and want to share with those who are also new to Arduino like me. This way, checking debounce is possible while the delay period.
void debounce_on(){ //same with bounce_off, the only difference is when debounce detected, execute on() function
** int start_time = millis();**
** while (state == HIGH){**
Sure, it works just fine, but the thing about the Bounce2 library is that it’s really hard to read and understand, especially for beginners.
TyZhang:
I tried to build a blink LED and doing debounce with delay() for the time between lights was frustrating because it nothing is processed during the delay time, which means that debounce can only be checked at a certain period. I wrote a function using millis() to replace delay() and want to share with those who are also new to Arduino like me. This way, checking debounce is possible while the delay period.
void debounce_on(){ //same with bounce_off, the only difference is when debounce detected, execute on() function
int start_time = millis();
while (state == HIGH){
bool newState = digitalRead(BUTTON_PIN);// check debounce
if (newState == HIGH && oldState == LOW){
delay(20);
newState = digitalRead(BUTTON_PIN);
if (newState == LOW) {
On(); //only difference here
}
if (dur <= millis() - start_time){
break;
}
}
}
Using the delay kind of defeats the whole point of using millis, and so does the while loop. What happens to oldState?
If you want to know how debouncing using millis works, I recommend you take a look at this example: PushButton-debounce.ino
It uses an object-oriented approach, which allows you to use multiple buttons in the same sketch.