Setting up debounce with millis()

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;**
** }**
** }**
}

Debounce.ino (1.89 KB)

... or you could just use the Bounce2 library.

See the Bounce2 library.

Thanks for sharing.

For most applications, all you need to do is check your switches every now and then, ex. 50ms.

There is still a delay(20); in there.

Better use a debounce library like vaj4088 mentionned.

Jacques

vaj4088:
… or you could just use the Bounce2 library.

See the Bounce2 library.

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.

Pieter

Sure, it works just fine, the thing about the Bounce2 library is that it's really hard to read and understand, especially for beginners.

Talking about simple, check this.

Jacques