SWITCH DEBOUNCE

Hi
I am not sure if this is the proper sub forum, but here is my question.
How input switch debounce issue is solved in arduino bords ?

Is it solved by software or hardware or both?
I am talking about a switch connected to an input port and the program is supposed to react to
switch status closed or open .

Thanks
Elico

Depends.

You have to have some different hardware than a bare Arduino to do it in hardware, so I usually debounce in software. Once I have hardware (which took a while to get a PCB laidout, made and stuffed), I remove the software debouncing.

Take a look at the debounce example that comes with the IDE for software debounce. Often though, rather than the use of millis as seen there, you'll see a simple use of a small delay.

While it's often convenient there is no need to use delay for debouncing. Here's a little snippet of code that I used recently for a button to switch the LCD backlight on or off. All it watches for is a state change. When that happens it starts debouncing. If it passes debouncing the actual state is used to decide the action to take. I know that debouncing is occurring when the debounceTime variable is non-zero.

  // handle button for backlight  
  static int buttonState_1 = HIGH;
  static unsigned long debounceTime_1 = 0;
  int currentButtonState = digitalRead(BUTTON_PIN_1);
  if (buttonState_1 != currentButtonState)
  {
    buttonState_1 = currentButtonState;
    debounceTime_1 = millis();
  }
  if (debounceTime_1 && millis() - debounceTime_1 >= DEBOUNCE_MILLIS)
  {
    debounceTime_1 = 0;
    if (buttonState_1 == LOW)
    {
      if (backLightState)
      {
        backLightState = false;
        lcd.noBacklight();
      }
      else
      {
        backLightState = true;
        lcd.backlight();
        backLightOnTime = now();
      }
    }
  }

That only takes an action on a LOW (pressed) value. It ignores releases only because it has nothing to do on release. Code could be added to take an action on release (HIGH) just as easily. I think the key is that you don't need to worry about the button's state when debouncing only that the state has changed. If it passes debouncing, then worry about the state.

ETA: That snippet is part of the loop() function.

Thanks
Elico

Delay is the wrong way to debounce. All that tells you is that a button down was detected, and another button down was detected right after the delay. Simple to mistakenly trigger that with noise.