Arduino Timer: play with timing in your projects

Hours Arduino UNO

Some time ago we published more information about the Arduino millis () function , now we will delve deeper into the Arduino Timer , to start working with this feature, understand how this MCU board manages time, as well as other functions beyond millis().

What is the Arduino Timer?

arduino timer

The Arduino timer, or timer , is a hardware-implemented function (in the microcontroller, using a quartz crystal that generates the clock pulses and sets the "rhythm," without the need for external hardware or 555 timer ICs) that allows you to control time events using internal clocks. For example, you can schedule a task to run at intervals, perform precise time measurements, etc., independently of the sketch code.

Just like Arduino UNO It has an MCU chip that works at 16 Mhz, 16.000.000 could be executed every second. The instructions need X cycles to execute, not all of them are executed in the same clock cycles, for example, the 16-bit ones need more cycles in this AVR architecture.

Imagine you use the `delay()` function ; this will block execution on the Arduino MCU until the specified time has elapsed, and then the program will continue. But with a timer, it won't block. It will be timing while the MCU continues executing other instructions simultaneously. That's the big advantage.

The timer is related to Arduino interrupts , as it will be executed through them to handle a specific task. In other words, the Arduino timer is a function that triggers at a predetermined time, executing an interrupt function. Therefore, understanding these interrupts is also important.

Modes

The Arduino Timer has 2 operating modes , allowing it to be used in:

  • PWM signal: You can control the Arduino pins (~).
  • CTC (Clear timer on compare match): counts the time inside a counter and when it reaches the value specified in a register of the timers, the interruption is executed.

How many timers does it have? Types of Timers

Arduino UNO millis functions

There are 3 timers on the plates Arduino UNO, although there may be more on other top plates:

  • timer 0: 8-bit, can count from 0 to 255 (256 possible values). Used by functions like delay(), millis(), and micros(). Its modification is not recommended so as not to alter the programs.
  • timer 1: equal to Timer 0. Used by the Servo library in UNO (Timer 5 for MEGA).
  • timer 2: 16-bit, and can range from 0 to 65.525 (65.536 possible values). Used for the tone() function, if not used, it can be used freely for your application.
  • Timer 3, 4, 5 (only on Arduino MEGA): all 16-bit.

How does the Arduino Timer work?

timers, timers

To work with an Arduino Timer , it is vital to understand how it all works electronically in the MCU of this development board:

  • Clock frequency: is the number of cycles per second that it is capable of developing, in the case of Arduino it is 16 Mhz, or what is the same, the clock signal oscillates 16.000.000 times in a second (cycles).
  • Period: is represented by the T, and is measured in seconds, and is the inverse of the cycles. For example, T=1/C, which would result in 1/16000000 = 0.0000000625, the time it would take for each cycle to complete. And the frequency is the inverse of the period, so f = 1/T.
  • Cycle: is each one of the repetitions of the signal that occur per unit of time. On Arduino it would be 16M in a second. Or what is the same, in this case, when 16 million cycles have passed, one second has passed. Therefore, one cycle can be said to take 625 ns.
  • edge of a signal: Clock signals are square, and the edges can be rising or falling. An edge is the straight line of the signal when it changes from:
    • 0 (low) to 1 (high): rising edge.
    • 1 (high) to 0 (low): falling edge.

Edges are important because Arduino timers measure cycles based on the signal's edges. Thus, the counter increments with each cycle, and when it reaches the register's value, the interrupt is triggered.

Therefore, once this is known, if the Arduino MCU operates at 16 MHz and uses an 8-bit timer, interrupts will occur every 16 µs (256/16000000) or 4 ms for 16-bit timers (65536/16000000). Therefore, if you configure the 16-bit counter register to its maximum value of 65535, the interrupt will occur every 4 ms to execute the desired task.

When the counter reaches its maximum possible value, it will reset to 0. In other words, an overflow occurs, and it will start counting again from the beginning.

To control the timer's increment rate, a prescaler can also be used , which takes values ​​1, 8, 64, 256, and 1024 and alters the timing in this way:

Timer Speed ​​(Hz) = Clock Frequency of Arduino / Prescaler

If the prescaler is 1, the controller will increment to 16 MHz; if it's 8, to 2 MHz; if it's 64, to 250 kHz, and so on. Remember that there will be a timer counter state comparator to compare the counter value and the prescaler value until they are equal, at which point an action is executed. Therefore, the interrupt frequency is given by the formula:

+1 is because the counter register is indexed at 0, i.e. it doesn't start counting at 1, but at 0.

Interrupt Speed ​​(Hz) = Arduino / Prescaler Clock Frequency (comparator register value + 1)

Fortunately, we don't need to modify the Arduino timer registers, as the libraries we use in the code will handle that. But if they aren't used, they should still be configured.

Examples in the Arduino IDE

Arduino IDE, data types, programming

In order to understand all this a little better, here I show two sketch codes for Arduino IDE with which you can get to experience the use of timers. The first is code that will blink an LED connected to Arduino pin 8 every second:

#define ledPin 8
void setup()
{
  pinMode(ledPin, OUTPUT);
  // Configurar Timer1
  TCCR1A = 0;                        //Registro control A a 0, pines OC1A y OC1B deshabilitados
  TCCR1B = 0;                        //Limpia el registrador
  TCCR1B |= (1<<CS10)|(1 << CS12);   //Configura prescaler a 1024: CS12 = 1 y CS10 = 1
  TCNT1 = 0xC2F8;                    //Iniciar timer para desbordamiento a 1 segundo
                                     //65536-(16MHz/1024/1Hz - 1) = 49912 = 0xC2F8 en hexadecimal
  
  TIMSK1 |= (1 << TOIE1);           //Habilitar interrupción para Timer1
}
void loop()
{
}
ISR(TIMER1_OVF_vect)                              //Interrupción del TIMER1 
{
  TCNT1 = 0xC2F7;                                 // Reniciar Timer1
  digitalWrite(ledPin, digitalRead(ledPin) ^ 1); //Invierte el estado del LED
}

Program the LED to blink or flash every second, as in the previous case, but this time using CTC, that is, comparison :

#define ledPin 8
void setup()
{
  pinMode(ledPin, OUTPUT);
  
  // Configuración Timer1
  TCCR1A = 0;                //Registro de control A a 0
  TCCR1B = 0;                //Limpiar registro
  TCNT1  = 0;                //Inicializar el temporizador
  OCR1A = 0x3D08;            //Carga el valor del registro de comparación: 16MHz/1024/1Hz -1 = 15624 = 0X3D08
  TCCR1B |= (1 << WGM12)|(1<<CS10)|(1 << CS12);   //Modo CTC, prescaler de 1024: CS12 = 1 y CS10 = 1  
  TIMSK1 |= (1 << OCIE1A);  //Habilita interrupción por igualdad de comparación
}
void loop()
{
}
ISR(TIMER1_COMPA_vect)          //Interrupción por igualdad de comparación en TIMER1
{
  digitalWrite(ledPin, digitalRead(ledPin) ^ 1);   //Invierte el estado del LED
}

More about Arduino programming

buy a plate Arduino UNO rev3
Add as preferred source in Google