# buttonled2.cpp

If we want to toggle an LED on each button push, it's critical that we register one and only one 'event' each time the button is pushed. But, when a mechanical button is pushed, the electrical signal usually bounces up and down for quite some time before settling, and while it's bouncing, calls on buttonDown() may return `true` and then `false` and then `true` again -- for a single button push.

'Debouncing' a button means ensuring only one event is detected per push. There are many ways to do it; this is one.

    // Toggle an LED each time the button is pushed.

    void setup() { /* nothing needed */ }

    bool ledIsOn = false;   // A variable to remember our state

    void loop() {

      // Wait for the button to be down for 10msecs in a row
      for (u32 i = 0; i < 10; ++i) {
        delay(1);
        if (!buttonDown())          // If the button's up, restart count
          i = 0;
      }

      ledIsOn = !ledIsOn;           // Flip the state of our variable
      ledSet(BODY_RGB_BLUE, ledIsOn);  // Turn LED on or off

      // Wait for the button to be up for 10msecs in a row
      for (u32 i = 0; i < 10; ++i) {
        delay(1);
        if (buttonDown())           // If the button's down, restart count
          i = 0;
      }
    }