Staying in a subroutine

I never miss an opportunity to look at debouncing code or strategy. Here we see something a bit different. The code in #14 stripped down to show just the debounce logic

#define SW 3 //define pin 3 as the select on rotary encoder

# define LED  4   // just an LED for showing

unsigned long lastButtonPress = 0; //records button press on rotary encoder

void setup() {

  pinMode(SW,INPUT_PULLUP); // setup rotary encoder SW as an input
  pinMode(LED, OUTPUT); // setup selector switch 
}

void menuSelect(){

  int btnState = digitalRead(SW); //read button state

  //if btnState LOW, then button is pressed
  if (btnState == LOW) {
    if (millis() - lastButtonPress > 500) {

      digitalWrite(LED, !digitalRead(LED)); // toggle the LED

    }
    lastButtonPress = millis(); // remember last button press
  }
}

void loop() {
    menuSelect();
}

is a demonstration of getting it right, albeit uncommon. The button is reacted to immediately, debouncing is handled by not reacting again until (at least) the debounce period has elapsed.

In the wokwi and above, I set the debounce period to an absurd 500 ms, just to show the effect. Most debouncing code waits that period before reacting. Replace 500 with 50 and you have an instant acting debounced button.

Try it.

a7

1 Like