millis (): everything you need to know about the Arduino function

Arduino UNO millis functions

Arduino has a good repertoire of functions to work with over time. One of them is millis (), an instruction that gives you the time in milliseconds since the Arduino board is turned on. This may seem absurd, and that it only serves to know when the plate was turned on, but the truth is that it has many more practical applications.

By example, it can be used to determine the time that has elapsed between two or more events, avoid the debounce (bounce) of a button, etc. It could also serve to show the execution time in critical stages of the code, ensuring that the program works in real time.

Millis () function

millis function Arduino

As I have already mentioned, the Arduino millis function is used to measure time, and it does so in milliseconds (ms), hence its name. In other words, the numerical value that this function returns when you include it in your sketch is a temporary data expressed in that unit.

You should know that the maximum value of this variable is unsigned long, that is, long without sign. This is important, because if a smaller one is used, logic problems could occur. In addition, you should know that it can last up to 50 days of time (4.320.000.000 ms), once it has reached that value it will restart and start again from zero.

Another thing you have to know is that the millis function does not use parameters.

Other temporary Arduino functions

Arduino has other time-related functions for you to use in your code. One of them is the famous delay (), but there is more:

  • delay (): It is the most used and common of all the Arduino functions. It also uses milliseconds as millis (). And it will also be of type unsigned long, in addition to not having a return value. It is mainly used to introduce pauses in the execution of a program, with many applications.
  • delayMicroseconds (): is less used in sketches, in this case it is still unsigned long, with no return value, and in this case it uses microseconds. Currently, a maximum value can be achieved with precision of 16383, and the minimum of 3μs. If you have to handle waits longer than that, it is recommended to use delay ().
  • micros (): also returns a numeric value in microseconds (μs) since the Arduino board started executing the program. That is, it is like millis (), but with another unit. In fact, it also uses the unsigned long type and it doesn't use parameters either. But it has some additional differences, such as that it resets and starts from zero when it reaches 70 minutes. Regarding its resolution of 4 μs, or in other words, the value it returns will always be a multiple of four (4, 8, 12, 16,…). Remember that 1000 μs equals 1 ms and 1.000.000 equals 1 s.

Millis () examples in Arduino IDE

Screenshot of Arduino IDE

These are all words, and the best view of the millis () function is by showing some examples of simple sketches in the Arduino IDE so that you can see some applications and use cases. So here are some practical examples...

Can be used with all Arduino boards

1-Example for explain the use from millis ():

unsigned long inicio, fin, transcurrido;  // Declarar las variables a usar
void setup(){
   Serial.begin(9600);  //Iniciar la comunicación serial
}
void loop(){
   inicio=millis();  //Consultar ms desde que inició la ejecución del sketch
   delay(1000);  //Espera 1 segundo
   fin=millis();  //Consultar ms fin del sketch
   transcurrido=fin-inicio;  //Calcula el tiempo desde la última lectura
   Serial.println(transcurrido);  //Muestra el resultado en el monitor serial
   delay(500);  //Esperar medio segundo
}

Measure the time between two serial messages:

unsigned long tiempo1 = 0;  //Declaramos las variables e iniciamos a 0
unsigned long tiempo2 = 0;
unsigned long diferenciaTiempo = 0;
void setup() {
  Serial.begin(9600);
  Serial.println("Envía la letra A/a por la terminal serial");
}

void loop() {
  if(Serial.available() > 0){
     char datoRecibido = Serial.read();
     if(datoRecibido == 'A' || datoRecibido == 'a'){
        tiempo1 = millis();
        Serial.println("Envía la letra B/b por la terminal Serial");
     }
     else if(datoRecibido == 'b' && datoRecibido == 'B'){
        tiempo2 = millis();
        diferenciaTiempo = tiempo1-tiempo2;
        Serial.print("El tiempo transcurrido entre el primer y último dato enviado es: ");
        Serial.print(diferenciaTiempo);
     }
   }
}

Doing blink an LED with millis ():

int estadoLed;  //Almacena el estado del LED (Encendido o apagado)
int periodo = 100;  //Tiempo que está el LED encendido o apagado
unsigned long tiempoAnterior = 0;  //Almacena tiempo de referencia para comparar
void setup() {
    pinMode(13,OUTPUT);  //Configura el pin 13 como salida para el LED
}
void loop() {
  if(millis()-tiempoAnterior>=periodo){  //Evalúa si ha transcurrido el periodo programado
    estadoLed=!estadoLed;  //Cambia el estado del LED cada 100ms
    digitalWrite(13,estadoLed);  //Actualiza el estado del LED al actual
    tiempoAnterior=millis();  //Almacena el tiempo actual como referencia
    }
}

Create a simple sequencer to send text through the serial monitor at different time intervals using millis ():

#define INTERVALO_MENSAJE1 3000
#define INTERVALO_MENSAJE2 5000
#define INTERVALO_MENSAJE3 7000
#define INTERVALO_MENSAJE4 15000
 
unsigned long tiempo_1 = 0;
unsigned long tiempo_2 = 0;
unsigned long tiempo_3 = 0;
unsigned long tiempo_4 = 0;
 
void print_tiempo(unsigned long tiempo_millis);
 
void setup() {
    Serial.begin(9600);
}
 
void loop() {
    if(millis() > tiempo_1 + INTERVALO_MENSAJE1){
        tiempo_1 = millis();
        print_tiempo(tiempo_1);
        Serial.println("Soy");
    }
   
    if(millis() > tiempo_2 + INTERVALO_MENSAJE2){
        tiempo_2 = millis();
        print_tiempo(tiempo_2);
        Serial.println("Un mensaje");
    }
   
    if(millis() > tiempo_3 + INTERVALO_MENSAJE3){
        tiempo_3 = millis();
        print_tiempo(tiempo_3);
        Serial.println("De");
    }
   
    if(millis() > tiempo_4 + INTERVALO_MENSAJE4){
        tiempo_4 = millis();
        print_tiempo(tiempo_4);
        Serial.println("Esperanza");
    }
}
 
void print_tiempo(unsigned long tiempo_millis){
    Serial.print("Tiempo: ");
    Serial.print(tiempo_millis/1000);
    Serial.print("s - ");
}

You already know that for more information you can download the free Arduino programming course in PDF.


Be the first to comment

Leave a Comment

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

*

*

  1. Responsible for the data: Miguel Ángel Gatón
  2. Purpose of the data: Control SPAM, comment management.
  3. Legitimation: Your consent
  4. Communication of the data: The data will not be communicated to third parties except by legal obligation.
  5. Data storage: Database hosted by Occentus Networks (EU)
  6. Rights: At any time you can limit, recover and delete your information.