Arduino: Millis() Cookbook

You’ve recently learned about millis() and can’t way to delete all of your references to delay().  The problem is that you don’t know quite how to convert your code into millis()-compatible code.  Here is a (running) list of millis() examples I’ve put together to help.  If you want to know when more are added make sure you subscribe to the RSS feed or email notification list.

  1. Police Lights – Flash two LEDs like strobing police lights
  2. Control ON and OFF time for a flashing LED. – More control than “blink without delay”
  3. Stopwatch Example – Calculate how much time code takes to execute
  4. Chasing LEDs – Larson-scanner style chasing pattern
  5. De-bounch a button (or switch) – No need for de-bouncing capacitor
  6. Delayed events after a button push – Timed events (button push is just example.)
  7. analogWrite() PWM Fading – No delay() and a simple function to keep a LED fading with PWM

You might also want to check out my “Blink Without Delay – Line by Line  Tutorial.” It is a much more in-depth explanation than the comments provided with the Arduino IDE example.

Your questions, comments, and even corrections are encouraged and very much appreciated! However. I have zero-tolerance for inappropriate or harassing comments. I try to reply to everyone... -James

Leave a comment

13 thoughts on “Arduino: Millis() Cookbook

  1. How to use millis command in coin slot operation? please help thanks. we cannot use delay because it disrupts the process.

  2. Hi i was wondering if you could help me out..i am trying to run a vibrator motor on my arduino along with two other sensors,i want the vibrator motor to start if any of the two sensors are continuously active for 2 minutes ..can you please help me modify my code for millis()

  3. Hi,
    I am trying to make LED blink at 0.7hz like turn signal of cars/motorcycles
    Trying to get it work like this:
    When a button on IR remote is pressed (hex code : 0x811), turn signal should start blinking at 0.7hz until a button on the remote is pressed again to turn it off (0x11).

    Is it possible? I’d really appreciate if you could help me with this.

    So far I have succeded to make LEDs on and off using IR remote buttons. But can’t get LEDs start blinking after pressing a key on IR remote and keep constantly blinking until IR remote button is pressed to turn it off.
    I have tried blink without delay example but couldn’t get it working.

    here is an example code i am using.

    #include <IRremote.h>
    #include <IRremoteInt.h>
    #define irPin 2 //IR receiver on pin 2
    int led1 = 3; //LED that turns on and off using IR remote button.
    int turn = 12; //turn indicator blinker. Should start blinking at 0.7hz after key on remote is pressed
    IRrecv irrecv(irPin);
    decode_results results;
    
    void setup() {
      Serial.begin(9600);
      irrecv.enableIRIn();
      pinMode(led1, OUTPUT);
      pinMode(turn, OUTPUT);
    
    }
    void loop() {
      if (irrecv.decode(&results)) {
        switch (results.value) {
    
          case 0x837: //IR remote key to turn LED1 ON
            digitalWrite(led1, HIGH);
            break;
    
          case 0x37: //IR remote key to turn LED1 OFF
            digitalWrite(led1, LOW);
            break;
    
          case 0x834: //I want to use this key to start blinking ‘turn’ LED at 0.7hz
            // don’t know what to do here
            break;
    
          case 0x34: //I want to use this key to stop blinking ‘turn’ LED
            // don’t know what to do here
            break;
    
        }
        irrecv.resume();
      }
    }
    
    • I would do something like this, using millis() and a flag variable. for your cases when you want to turn the LED on and off, you just set the flag. this way each time loop() runs, if the flag is on, the blink is done.

      (I don’t have an arduino with me to test this code.)

      You can also download here: https://pastebin.com/prQqTWG0

      #include <IRremote.h>
      #include <IRremoteInt.h>
      #define irPin 2 //IR receiver on pin 2
      
      
      int led1 = 3; //LED that turns on and off using IR remote button.
      int turn = 12; //turn indicator blinker. Should start blinking at 0.7hz after key on remote is pressed
      
      bool blinking = false;  //defines when blinking should occur
      unsigned long blinkInterval = 1420;  // number of milliseconds for blink (1/0.7)
      
      unsigned long currentMillis; // variables to track millis()
      unsigned long previousMillis; 
      
      IRrecv irrecv(irPin);
      decode_results results;
      
      void setup() {
        Serial.begin(9600);
        irrecv.enableIRIn();
        pinMode(led1, OUTPUT);
        pinMode(turn, OUTPUT);
      }
      void loop() {
        
        // this code blinks the LED 
        if (blinking) {    
          currentMillis = millis();  // better to store in variable, for less jitter
          if ((unsigned long)(currentMillis - previousMillis) >= blinkInterval) {  // enough time passed yet?
            digitalWrite(turn, !digitalRead(turn));  // shortcut to toggle the LED
            previousMillis = currentMillis;  // sets the time we wait "from"
          }
        } else {
          digitalWrite(turn, LOW); // force LED off when not blinking
        }
        
        if (irrecv.decode(&results)) {
          switch (results.value) {
      
            case 0x837: //IR remote key to turn LED1 ON
              digitalWrite(led1, HIGH);
              break;
      
            case 0x37: //IR remote key to turn LED1 OFF
              digitalWrite(led1, LOW);
              break;
      
            case 0x834: //I want to use this key to start blinking ‘turn’ LED at 0.7hz
              blinking = true;
              break;
      
            case 0x34: //I want to use this key to stop blinking ‘turn’ LED
              blinking = false;
              break;
      
          }
          irrecv.resume();
        }
      }
      
      • Wow. it works

        Thanks alot, you’re the man. 🙂
        I was trying to figure it out for ages. Really appreciate your help.

        Thanks again.

  4. Hi,

    Wondered if you can assist/ point me in the right direction?
    I am thinking about measuring the Overall Equipment Effectiveness of a machine (OEE) via a retro-fitted status box.

    Initial thoughts are to have a sensor measuring the speed
    While the speed is being in the High status no event
    When the speed = 0 [i.e. the machine stops]
    I am wanting to record the real time it actually stopped

    Then the operator will activate a condition toggle for an array of 3 conditions
    1. Waiting for a Material
    2. Waiting for an engineer
    3. Defect

    When the toggle condition is induced this is to be timed (real time)

    until the condition is cleared and the machine runs

    Could you give me a clue where to find a similar program please?

    Thanks in advance

    • I doubt you’ll find an exact match.

      An alternative to a microcontroller based solution would be using a programmable logic controller (PLC). They’re industrial microcontrolllers with programming “languages” designed specifically for working with machines.

  5. Hi, HELP please…
    i want to remove all the delays from the codes below:v

    void loop(){
    northtogreen(); //change the north signal to green
    delay(maindelay*4); //wait for the traffic to pass
    northtored(); //change the north signal back to red
    delay(maindelay/2); //small delay to allow traffic to clear junction
    easttogreen(); //change the east signal to green
    delay(maindelay*4);//wait for the traffic to pass
    easttored(); //change the east signal back to red
    delay(maindelay/2); //small delay to allow the traffic to clear junction

    }
    void northtogreen(){ //sequence of north lights going to green

    digitalWrite(northAmber,HIGH); //Amber on, prepare to go
    delay(maindelay); //Time for traffic to see amber
    digitalWrite(northRed,LOW); //red off, finished with
    digitalWrite(northAmber,LOW); //amber off, finished with
    digitalWrite(northGreen,HIGH); //green on, go

    }
    void northtored(){ //sequence of north lights going to red

    digitalWrite(northAmber,HIGH); //Amber on, prepare to stop
    digitalWrite(northGreen,LOW); //Green off, finished with
    delay(maindelay); //Time for traffic to stop
    digitalWrite(northAmber,LOW); //Amber off
    digitalWrite(northRed,HIGH); //Red on, stop

    }

    void easttogreen(){ //sequence of east lights going to green

    digitalWrite(eastAmber,HIGH); //Amber on, prepare to go
    delay(maindelay); //Time for traffic to see amber
    digitalWrite(eastRed,LOW); //red off, finished with
    digitalWrite(eastAmber,LOW); //amber off, finished with
    digitalWrite(eastGreen,HIGH); //green on, go

    }

    void easttored(){//sequence of east lights going to red

    digitalWrite(eastAmber,HIGH); //Amber on, prepare to stop
    digitalWrite(eastGreen,LOW); //Green off, finished with
    delay(maindelay); //Time for traffic to stop
    digitalWrite(eastAmber,LOW); //Amber off, finished with
    digitalWrite(eastRed,HIGH); //Red on, stop

    }

    thanks 🙂

    • It really isn’t a simple method like “replace” the calls to delay(). You need to create a state machine. (Which will be a topic for a future post). A state machine is where you create one or more variables that tell your code what to do at certain times. So for example you might have a “AmberState”. When State is 0, the pin is off for 500ms. After 500ms you change the state to 1. Whenever the state is 1 you turn on the pin. When another 500ms passes, you set it back to 0.