Advertisement
baldengineer

Pushbutton start / stop LED blinking

May 5th, 2015
1,462
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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. by: james@baldengineer.com
  5. */
  6. const byte button=2;
  7. const byte LED=10;
  8.  
  9. bool blinking = false;  //defines when blinking should occur
  10. unsigned long blinkInterval = 250;  // number of milliseconds for blink
  11. unsigned long currentMillis; // variables to track millis()
  12. unsigned long previousMillis;
  13.  
  14. void setup() {
  15.   pinMode(button, INPUT);
  16.   pinMode(LED, OUTPUT);
  17. }
  18.  
  19. void loop() {
  20.   // this code blinks the LED
  21.   if (blinking) {    
  22.     currentMillis = millis();  // better to store in variable, for less jitter
  23.     if ((unsigned long)(currentMillis - previousMillis) >= blinkInterval) {  // enough time passed yet?
  24.       digitalWrite(LED, !digitalRead(LED));  // shortcut to toggle the LED
  25.       previousMillis = currentMillis;  // sets the time we wait "from"
  26.     }
  27.   } else {
  28.     digitalWrite(LED, LOW); // force LED off when not blinking
  29.   }
  30.   int reading = digitalRead(button);
  31.   delay(50); // crude de-bouncing
  32.  
  33.   if (reading==LOW) // buttons with pull-up are pressed when LOW
  34.     blinking=true; // start blinking
  35.   else
  36.     blinking=false; // stop blinking
  37. }
Advertisement
RAW Paste Data Copied
Advertisement