Advertisement
kowalyshyn_o

Push Button with Debounce

Jun 20th, 2016
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.96 KB | None | 0 0
  1. /* A digital push button switch
  2. Push button toggle switch code with debounce time for Lilypad
  3.  
  4. Takes a push button switch as input in an LED in a circuit.
  5. Each press of the button toggles the LED state ON or OFF.
  6.  
  7. Debounce code ignores mechanical noise in the switch producing a
  8. clean ON or OFF state.
  9.  
  10. Written by Orwell Kowalyshyn for theMakery.space
  11. Portions of code from Arduino.cc
  12. */
  13.  
  14. const int buttonPin = 5;          //define the push button and LED pin ports as constants
  15. const int ledPin = 6;
  16.  
  17. int reading;                      //variable for switch state - open is HIGH, closed is LOW
  18. int state = HIGH;                 //pin is turned on to start
  19. int debounce = 300;               //200 millisecond debounce time
  20. long timing = 0;                  //set program running time to 0, 32-bit size
  21.  
  22. void setup() {
  23.  
  24.   pinMode(buttonPin,INPUT_PULLUP);  //enable input pullup resistor on pin, default to high impedence state
  25.   pinMode(ledPin, OUTPUT);          //set output for LED
  26.  
  27.   digitalWrite(ledPin,state);       //turn LED on by default
  28. }
  29.  
  30. void loop() {
  31.  
  32.   reading = digitalRead(buttonPin);   //get state of the button, HIGH (open) or LOW (closed)
  33.  
  34.   if (reading == LOW && state == LOW && (millis()-timing > debounce)) {         //button action close, and LED is off, and > debounce time
  35.     state = HIGH;                                                               //turn on LED
  36.     timing = millis();                                                          //mark time when state changed                                                    
  37.   }
  38.  
  39.   else if (reading == LOW && state == HIGH && (millis()-timing > debounce)) {    //button closed and LED is on, and > debounce time
  40.     state = LOW;                                                                 //turn off LED
  41.     timing = millis();                                                           //mark time when state change
  42.   }
  43.  
  44.   digitalWrite(ledPin,state);         //set LED state
  45.  
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement