Advertisement
Guest User

Arduino modified debounce

a guest
May 23rd, 2012
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.24 KB | None | 0 0
  1. /*
  2.  Debounce toggle
  3.  
  4. This code is in the public domain.
  5.  
  6. Original code at http://www.arduino.cc/en/Tutorial/Debounce
  7.  
  8. */
  9.  
  10. const int buttonPin = 2;    // the number of the pushbutton pin
  11. const int ledPin = 13;      // the number of the LED pin
  12.  
  13. int ledState = HIGH;         // the current state of the output pin
  14. int buttonState;             // the current reading from the input pin
  15. int lastButtonState = HIGH;  // the previous reading from the input pin
  16. int isOn = 0;                // the current state of the LED
  17.  
  18. long lastDebounceTime = 0;  // the last time the output pin was toggled
  19. long debounceDelay = 30;    // the debounce time; increase if the output flickers
  20.  
  21. void setup() {
  22.   pinMode(buttonPin, INPUT_PULLUP);
  23.   pinMode(ledPin, OUTPUT);
  24. }
  25.  
  26. void loop() {
  27.   // read the state of the switch into a local variable:
  28.   int reading = digitalRead(buttonPin);
  29.  
  30.   // check to see if you just pressed the button
  31.   // (i.e. the input went from LOW to HIGH),  and you've waited
  32.   // long enough since the last press to ignore any noise:  
  33.  
  34.   // If the switch changed, due to noise or pressing:
  35.   if (reading != lastButtonState) {
  36.     // reset the debouncing timer
  37.     lastDebounceTime = millis();
  38.   }
  39.  
  40.   if ((millis() - lastDebounceTime) > debounceDelay) {
  41.     // whatever the reading is at, it's been there for longer
  42.     // than the debounce delay, so let's do our button action
  43.     if(reading == LOW && isOn == 0) {          // Is the button in a pushed state and LED is off?
  44.       do
  45.       {
  46.         digitalWrite(ledPin, HIGH);            // Turn it on
  47.         isOn = 1;                              // and set the variable for the next go around
  48.       } while(digitalRead(buttonPin) == LOW);  // Don't stop until we actually let go of the button  
  49.     }
  50.    
  51.     else if(reading == LOW && isOn == 1) {     // Is the button in a pushed state and LED is on?
  52.       do
  53.       {
  54.         digitalWrite(ledPin, LOW);             // Turn it off
  55.         isOn = 0;                              // set variable to off
  56.       } while(digitalRead(buttonPin) == LOW);  // Don't stop until button is let go of
  57.     }
  58.   }
  59.   // save the reading.  Next time through the loop,
  60.   // it'll be the lastButtonState:
  61.   lastButtonState = reading;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement