baldengineer

Timed events with millis()

Jan 19th, 2016
2,166
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //Global Variables
  2. const byte BUTTON=2; // our button pin
  3. const byte LED=13;   // LED (built-in on Uno)
  4.  
  5. unsigned long buttonPushedMillis;  // when button was released
  6. unsigned long ledTurnedOnAt;  // when led was turned on
  7. unsigned long turnOnDelay = 2500; // wait to turn on LED
  8. unsigned long turnOffDelay = 5000; // turn off LED after this time
  9. bool ledReady = false; // flag for when button is let go
  10. bool ledState = false; // for LED is on or not.
  11.  
  12. void setup() {
  13.   pinMode(BUTTON, INPUT_PULLUP);
  14.   pinMode(LED, OUTPUT);
  15.   digitalWrite(LED, LOW);
  16. }
  17.  
  18. void loop() {
  19.   // get the time at the start of this loop()
  20.   unsigned long currentMillis = millis();
  21.  
  22.   // check the button
  23.   if (digitalRead(BUTTON) == LOW) {
  24.    // update the time when button was pushed
  25.    buttonPushedMillis = currentMillis;
  26.    ledReady = true;
  27.   }
  28.  
  29.   // make sure this code isn't checked until after button has been let go
  30.   if (ledReady) {
  31.     //this is typical millis code here:
  32.     if ((unsigned long)(currentMillis - buttonPushedMillis) >= turnOnDelay) {
  33.        // okay, enough time has passed since the button was let go.
  34.        digitalWrite(LED, HIGH);
  35.        // setup our next "state"
  36.        ledState = true;
  37.        // save when the LED turned on
  38.        ledTurnedOnAt = currentMillis;
  39.        // wait for next button press
  40.        ledReady = false;
  41.     }
  42.   }
  43.  
  44.   // see if we are watching for the time to turn off LED
  45.   if (ledState) {
  46.     // okay, led on, check for now long
  47.     if ((unsigned long)(currentMillis - ledTurnedOnAt) >= turnOffDelay) {
  48.       ledState = false;
  49.       digitalWrite(LED, LOW);
  50.     }
  51.   }
  52. }
  53.  
  54. /* Code Example on how to create virtual delays using Arduino Millis()
  55. ** written by James at www.baldengineer.com
  56. **
  57. ** For more examples and full explanation visit:
  58. ** https://www.baldengineer.com/use-millis-with-buttons-to-delay-events.html
  59. */
RAW Paste Data