Arduino Millis() Examples

Example code using millis()

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.

Baldengineer’s Arduino millis() Examples

  1. Arduino Multitasking – Step by step examples of how to convert delay() code into millis() based code, to simulate multitasking.
  2. Police Lights – Flash two LEDs like strobing police lights
  3. Control ON and OFF time for a flashing LED. – More control than “blink without delay”
  4. Stopwatch Example – Calculate how much time code takes to execute
  5. Chasing LEDs – Larson-scanner style chasing pattern
  6. De-bounch a button (or switch) – No need for de-bouncing capacitor
  7. Delayed events after a button push – Timed events (button push is just example.)
  8. analogWrite() PWM Fading – No delay() and a simple function to keep a LED fading with PWM
  9. Detect Short and Long Button Press – Give one button multiple functions

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.

Long comments, URLs, and code tend to get flagged for spam moderation. No need to resubmit.

ALL comments submitted with fake or throw-away services are deleted, regardless of content.

Don't be a dweeb.

Leave a comment

59 thoughts on “Arduino Millis() Examples

  1. Hi Tim,

    I´m trying to use millis() to control the DC motors of my Sumorobot. My problem is that when i try to use millis my code doesnt work correctly, but when i use delay it works well. I know that im making mistakes when I change my code from delay () to millis(). Can you send me an email to help me? I need help, its for a proyect with my secondary school. Thanks and respects from argentina.

    • You cannot replace delay() with millis(). You must re-write the logic of your code. Unfortunately, I do not provide one-on-one email help. I would suggest posting your code and question on the “Programming Guidance” section of the fourms.

  2. Hi Tim,

    (From one bald engineer to another…)

    I tried using the millis() approach to multi-task my Arduino but unfortunately it didn’t work. It turned out that the processing time to read a couple of sensors and perform some math on the results was so long (hundreds of milliseconds) that other tasks (flashing led’s based on results) didn’t get updated in time, so the flashing sequences were completely messed up. Any suggestions?

      • Thanks James ( sorry I called you Tim!). I’ll give that a try and let you know how it works out. As I am using standard Arduino library routines to deal with the sensors, it may then become necessary to copy the library code directly into my sketch and modify it to make the function calls at the appropriate times…assuming the library code is in the public domain.

  3. Oh I forgot to add, and can see why this is creating some confusion,

    the front and rear lights are off the same pin (im using a mosfet to drive the leds, in parallel, all white, no issue so far

    and the side maker lights are another pin, mosfet etc, so there are only 2 pins, just need another funcition

    sorry for the lack of info..

    • Hi Tim,
      Here is a simpler program. No Mode, only Patterns, You could modify at will each pattern or add new pattern just be sure to update the MaxPattern definition if you do,
      Since we have went around this program a lot, the other readers of this Millis() collumn will find boring reading all of our discussions so If you need other modification or need some clarifications, feel free to contact me using my email. Just use my username and add email to it then ampersand then
      I will be pleased to help you.

      // Arduino program for Strobing Bicycle Lights V 1.00
      // In this program 4 patterns for 2 lights blinking are sequentially selected by a push button
      // Patterns are kept in a 2 dimension Matrix named Event 
      // The corresponding delays is in the Matrix Delays
      #define MaxPattern	4			// Number of pattern of blinking light
      #define MaxEvent	9			// Number of max blinking event
      #define ledwstrobe	2			// Define white led pin
      #define ledrstrobe	3			// Define Red led pin
      #define ButtonPin	4			// Define push Button pin. other side connected to ground
      // Type of event possible
      enum EventType {None,BothLo,BothHi,RedLo,RedHi,WLo,WHi};   		
      // Actual event suite for each pattern. If you have less than MaxEvent, fill with None
      EventType Event[MaxPattern][MaxEvent] =   {{BothHi,None,None,None,None,None,None,None,None},
      // Actual delay suite for each pattern. If you have less than MaxEvent, fill with 0 delay
      int Delays[MaxPattern][MaxEvent] =  {{0,0,0,0,0,0,0,0,0},
      unsigned long NextEventTime = 0;   		// When millis() >= NextEventTime then Event is due
      unsigned long LastDebounceTime = 0;		// When millis() >= NextButtonTime then bounce time is due 
      unsigned long DebounceDelay = 50;		// 50ms for general debounce delay
      int Pattern = 0;							// Keep track on the next pattern. Value 0 - MaxPattern-1
      int NextEvent = 0;            			        // Keep track of the next event. Value 0 - MaxEvent-1
      int ButtonState = HIGH;   				// Variable for current button reading
      int LastButtonState = HIGH;				// Variable for last known button reading
      void setup() {
           pinMode(ledwstrobe,OUTPUT);			// white LED
           pinMode(ledrstrobe,OUTPUT);			// red LED
           pinMode(ButtonPin,INPUT_PULLUP);	// put the button to ground to activate
      void loop() {
      	// Check the push button
      	int reading = digitalRead(ButtonPin);
      	//in the case that the reading is not equal to the last state set the last debounce time to current millis time
      	if (reading != LastButtonState)  {
      		LastDebounceTime = millis();
      	//check the difference between current time and last registered button press time, if it's greater 
      	if ((millis()-LastDebounceTime) > DebounceDelay) {
      		if (reading != ButtonState) {
      			ButtonState = reading;
      			if (ButtonState == LOW) {						                // Button Pushed !
      				Pattern++;										//	increment Pattern Index
      				if (Pattern == MaxPattern) Pattern=0;	// Roll over if Mode is too big
      				NextEvent = 0;						     			       // Reset to first Event
      				NextEventTime = millis();					               // Reset the Nextime Event Delay
      	LastButtonState = reading;								              // Keep the last button state
      	if (millis() >= NextEventTime) GoBlink();
         // do whatever here 
      // Do the actual blinking
      void GoBlink() {
      // If we find None return to the start of the list
      	if (Event[Pattern][NextEvent] == None) NextEvent = 0;
      // Do the blink indicated by the NextEvent for the current pattern
         switch (Event[Pattern][NextEvent]) {
            case BothLo:
            case BothHi:
            case RedHi:
            case RedLo:
            case WHi:
            case WLo:
      		case None:
      // Add the next delay to millis() and increment tne NextEvent counter
         NextEventTime = millis() +  Delays[Pattern][NextEvent];
      // if we have attained the end of the list, return to the beginning
         if (NextEvent == MaxEvent) NextEvent = 0;