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 lightOn = 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;
  }

  lightOn = !lightOn;           // Flip the state of our variable
  ledSet(BODY_RGB_BLUE_PIN, lightOn);  // 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;
  }
}

Generated on Fri Apr 22 06:54:10 2011 for SFB by doxygen 1.5.9