In a previous article, we used the TimerOne library to add timer interrupts to Arduino. But what if we wish to generate timer interrupts without a third-party library? In that case, you will directly have to meddle with the timer registers in Arduino. In this article, we will just introduce the registers relevant to timer operations and explain their significance. We will also provide the page numbers of the ATmega328 (used in Arduino Uno) datasheet wherein you can find detailed information on these registers.
You can find the datasheet here −https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf
These are timer control registers. The x stands for the timer number. If you are using Timer0, you will be concerned with TCCR0A and TCCR0B registers. The TCCR0A register (primarily the WGM00 and WGM01 bits, along with WGM02 bit from TCRR0B register), control the counting sequence of the counter.
Have a look at the image below −
Generally, one of Normal or CTC modes is used. In normal more, you don’t care about the exact time interval. If you have an 8-bit counter, you set its value to 0, wait it to reach 0xFF (0xFFFF for 16 bit) and then the interrupt is generated. In the CTC (Clear Timer on Compare) mode, the interrupt is generated when the value of the counter reaches the value set in OCRA register. This gives you more control on the time interval.
The CS00, CS01 and CS02 bits of TCCR0B are used to set the prescaler of the clock. See the image below −
This register is where the actual counting happens. It is generally initialized with 0. It’s value is compared with the Output Compare Register (in CTC mode), and an interrupt is generated when the values match.
This is the register which holds the number of ticks required for generating the required delay. The value of TCNTx is continuously compared with OCRxA and when the values match, the interrupt is generated
Generally, only the 0CIE0A bit is important here. It has to be set to 1 to enable the interrupt when TCNT register value reaches OCRA value.