Advertisement
baldengineer

Pushbutton start / stop LED blinking

May 5th, 2015
1,854
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.25 KB | None | 0 0
  1. /*
  2. Example to use a pushbutton to start or stop a blinking LED, using millis()
  3. More at : http://www.baldengineer.com/pushbutton-and-flashing-led-tutorial-with-millis.html
  4. */
  5. const byte button=2;
  6. const byte LED=10;
  7.  
  8. bool blinking = false;  //defines when blinking should occur
  9. unsigned long blinkInterval = 250;  // number of milliseconds for blink
  10. unsigned long currentMillis; // variables to track millis()
  11. unsigned long previousMillis;
  12.  
  13. void setup() {
  14.   pinMode(button, INPUT);
  15.   pinMode(LED, OUTPUT);
  16. }
  17.  
  18. void loop() {
  19.   // this code blinks the LED
  20.   if (blinking) {    
  21.     currentMillis = millis();  // better to store in variable, for less jitter
  22.     if ((unsigned long)(currentMillis - previousMillis) >= blinkInterval) {  // enough time passed yet?
  23.       digitalWrite(LED, !digitalRead(LED));  // shortcut to toggle the LED
  24.       previousMillis = currentMillis;  // sets the time we wait "from"
  25.     }
  26.   } else {
  27.     digitalWrite(LED, LOW); // force LED off when not blinking
  28.   }
  29.   int reading = digitalRead(button);
  30.   delay(50); // crude de-bouncing
  31.  
  32.   if (reading==LOW) // buttons with pull-up are pressed when LOW
  33.     blinking=true; // start blinking
  34.   else
  35.     blinking=false; // stop blinking
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement