Learn to code

ARDUINO & CODES

Previous Post
Creating Custom Characters on a 16×2 LCD with Arduino
Next Post
Create a Touch Button with copper /aluminum foil

Use the millis() function instead of delay() function for Arduino

in Arduino Times and Dates

In this tutorial, you will learn how to use the millis() function instead of the delay() function. While the delay() function can be useful, especially in prototyping, it also has its limitations. The biggest limitation of the delay() functions is that your code cannot do something else within the code. This problem can be solved by using the millis() function. The function returns the time in milliseconds that the Arduino Board is powered and running a program.

The millis() function enables us to work with time and delays without stopping the entire code.

Millis(): counts the number of milliseconds that the sketch has been running.

What is the millis() function

So, the millis() functions return the number of milliseconds passed since the Arduino Board began running the program. This number will overflow (go back to zero) after approximately 50 days.

The most simple way to review this function is to look at a simple sketch.

void setup() {
  Serial.begin(9600);
}
void loop() {
  Serial.println( millis() );

}

 

As you can see we start by beginning Serial Communication and then we will use the function Serial.println to print the value of millis tot he Serial Monitor. If you open the Serial Monitor you will see that the value of millis is increasing rapidly.
The function returns the number of milliseconds that the Board is powered.

Essentially the function is a timer for how long the current program has been running. It does matter how often the void loop has iterated.

I would not recommend it, but if you would like to see the maximum number that the millis() function can run you will have to wait 4,294,967,296 milliseconds, or 49 days before it will overflow.

Therefore, when you are using variables associated with millis(), always declare them as an unsigned long integer. This enables us to see the time that is passed. So instead of waiting a certain amount of time, such is done by delay(), you can use millis() instead.

Code Example

We can use the above explanation to write our first line of coding with the millis() function. One of the first commands that you have learned is the IF Statement.

const unsigned long event = 1000;

void setup() {
}
void loop() {

  if ( millis() > event ) {

        Serial.println("You just learned something about millis()");
    
  }
}

The code above will sends text to the Serial Monitor after 2000 milliseconds. This is acheived by assigning a long unsigned constant variable that holds the amount of milliseconds that corresponds to 2 seconds. It is a constant variable because the variable will not change in the program.

In the void loop() we are going to create a IF statements that checks the current millis() against the variable that holds the 2 seconds. IF millis() is greater than 2000, the code inside the curly brackets is executed.

This is a relative simple usage of the millis() function. Let us continue to a bit more complicated code.

Repeating with millis()

In this example, we will write a bit more complicated code. The example will show how you can repeat an event every 2 seconds. You can change the repeating time as is needed. You can imagine that this can be used in a variety of programs such as measuring the moisture every minute or turning a servo motor every 30 seconds. Let us take a look at the code.

const unsigned long interval = 2000;
unsigned long previousTime = 0;

void setup() {
  Serial.begin(9600);
}

void loop() {

  /* Updates frequently */
  unsigned long currentTime = millis();

  /* This is the repeating part every 2 seconds*/
  if (currentTime - previousTime >= interval) {
    /* Put here your code that is repeated */
    Serial.println("You just learned something about millis()");
    
   /* Updating the time to enable a repeating proces */
    previousTime = currentTime;
  }
}

Constant variables

Firstly, we need to define a variable to holds our “delay” time. In other words, we are defining a variable that holds the amount of time that is passed between the execution of the code.

To be able to repeat a part of the code every … milliseconds we want to know the current elapsed time and the previous time that the code was executed. This is quite difficult to understand sol lets clarify this with an example.

We want to print our text every 2 seconds tot the Serial Monitor. If the program starts millis() will remember the current time. We need to compare this with another time to know whether or not the 2 seconds are passed. Therefore we need to declare a variable that holds the previous time.

So we are going to create a variable that is used to update the time, called previousTime.

const unsigned long interval = 2000;
unsigned long previousTime = 0;

Capture current millis()

Next, we are going to start serial communication by using the Serial.Begin() command.

We arrived at a very interesing part of the sketch. In the void loop(), we are executing the code that enables us to repead something without using delay(). First, we need to get the current time by callling the millis() function and storing it in a unsigned long variable that is called currentTime. Every time the loop is started the currentTime will hold the current value of the millis() function.

void setup() {
  Serial.begin(9600); void loop() {

/* Updates frequently */
unsigned long currentTime = millis();
}

IF Statement

After this, we need to create something that will happen if millis() is at our interval time.

The IF statement takes the current time and then subtracts it from the previous time. It then checks if the result is greater or equal to the value of the variable interval. Note that the current time is constantly updated by the beginning of each iteration of the loop. We also defined that the interval time will not change.

By assigning numbers to the iterations I hope that it will be more clear.

/* This is the repeating part every 2 seconds*/
  if (currentTime - previousTime >= interval) {
    /* Put here your code that is repeated */
    Serial.println("You just learned something about millis()");
    
   /* Updating the time to enable a repeating proces */
    previousTime = currentTime;
  }
}

Constant variables

At the beginning of the program, currentTime will be a very small number since the program has just begun. Let’s assume that the program is 0.5 seconds underway (500 milliseconds). The difference between currentTime (500) and previousTime is (0) is 500. This is not equal or greater than our interval time of 2000. Therefore, the IF statement is FALSE and the code inside the brackets is not executed. After this, we are going back to the beginning of the loop function.

Next, assume that 1000 milliseconds have passed. There will be the same outcome as with 500 milliseconds. The program will continue through the loop until the IF statement is TRUE, which will happen after 2000 milliseconds.

After 2000 milliseconds, 2 seconds, have passed. Therefore, currentTime (2000) – perviousTime(0) = 2000 which is equal tot he interval variable of 2000. Now the code within the IF statement is executed.

Now we encounter a clever part of the milis() function. It is possible to print this message every 2 seconds.
So previousTime was 0, it is updated with the currentTime (2000). So after 2 seconds, previousTime will be 2000. Now the loop is ended and it will start over again.

After 3 seconds, the currentTime will be 3000 milliseconds and the previousTime 2000 milliseconds. 3000-2000 =1000 which makes the IF Statement FALSE. After 4000 milliseconds the difference is again 2000 and the text is printed again on the Serial Monitor.

The above explanation shows how millis() can be used for a repetitive event on Arduino.

In this tutorial I have demonstrated how you can use the millis() function instead of the delay() function. We used this function to print text on tot he Serial Monitor.

I hope that you enjoyed reading the tutorial and fount is useful and informative. If you did please subscribe to my Instagram or Pinterest account found at the top of this page.

In any case that you have questions, feel free to ask them in the comments.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu