Advertisement
baldengineer

Toggling Button

Jan 1st, 2017
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.04 KB | None | 0 0
  1. const int  buttonPin = 2;    // the pin that the pushbutton is attached to
  2. const int ledPin = 13;       // the pin that the LED is attached to
  3.  
  4. // Variables will change:
  5. int buttonState = 0;         // current state of the button
  6. int lastButtonState = 0;     // previous state of the button
  7. int ledState = false;
  8.  
  9. void setup() {
  10.   // initialize the button pin as a input:
  11.   pinMode(buttonPin, INPUT_PULLUP);
  12.   // initialize the LED as an output:
  13.   pinMode(ledPin, OUTPUT);
  14. }
  15.  
  16.  
  17. void loop() {
  18.   // read the pushbutton input pin:
  19.   buttonState = digitalRead(buttonPin);
  20.  
  21.   // compare the buttonState to its previous state
  22.   if (buttonState != lastButtonState) {
  23.     // change detected, if button is down (inverted since pullup),
  24.     // invert led state
  25.     if (buttonState == LOW)
  26.       ledState = !ledState;
  27.     digitalWrite(ledPin, ledState);
  28.      // Delay a little bit to avoid bouncing
  29.     delay(50);
  30.   }
  31.  
  32.   // save the current state as the last state,
  33.   //for next time through the loop
  34.   lastButtonState = buttonState;
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement