Millis Function of Arduino

What is Millis function of Arduino?

A millis function of Arduino have a name of ‘millis’ because it calculates time consumed during the execution of code in milli seconds. Whenever you call the function in the code, it will give the total time consumed since the starting of the code execution till the calling of function.

For example if an Arduino loop function have delay of 1 second then millis function will give 1000 in the result of calling the function, after 1st loop it will give 2000 answer and so on. It means the execution of one loop is taking 1000 milli seconds to complete the loop.

Example of millis function

Let’s have a look on the example below:

void setup() {
Serial.begin(9600);
}
void loop() {
double milfunc = millis();
Serial.print("millis function=");
Serial.println(milfunc);
delay(1000);
}

Result:

1st Result of millis function
Figure 1: 1st Result of millis function

The above image is clearing the concept of millis function of Arduino easily.

Two different ways to use millis function of Arduino

There are two different ways to use millis function.

One way is to use it directly and get the entire time of execution. This can be seen in the example above. After every loop millis function is returning the value with respect to the starting of the execution.

Now, let’s have a look on the second and more important way of using the millis function. Millis function can be used in such a way that after each loop it will return the total time consumption of that loop. This way is more important because during different measurements, compiler have to wait for some specific point to start the execution again. So millis function can easily give that difference of that two time periods. Let’s see another example of millis function regarding this way of using it.

int milold=0;
int milnew=0;
void setup() {
Serial.begin(9600);
}
void loop() {
milnew =  millis() - milold;
milold = millis();
Serial.print("Result=");
Serial.println(milnew);
delay(1000);
}

Result:

2nd Result of Millis Function
Figure 2: 2nd Result of Millis Function

You can have a look on the practical examples of this awesome millis function of Arduino:

Tachometer using Arduino and Hall Sensor

3 phase Smart Energy Meter

To share your point of view on this article, comment below and don’t forget to like our facebook page.

Ismail Sarwar

Electrical engineering is my profession, my hobby and my passion. I completed bachelors of electrical engineering in 2015. Currently I am working with an Electric Utility Company. Power Electronics, Embedded Systems and Energy Metering are my fields of specialization. In free time I listen music and watch movies.

What do you think?