What TIMERx is?
Hardware timers are very important modules in every microcontroller. They let to do many things, but for a beginner as I am most important thing that they let do is accurate time period measuring. So there is no need to use _delay_ms function. In very short words TIMER is a counter that counts impulses from a prescaler which divide a microcontroller clock source. It is very powerfull and usefull tool that could be used in many projects in diffrent ways. Today I write about initialisation of timer in CTC mode that can count impulses determined number of times. The number of impulses that it will count it settable in the OCRx register.
Registers
The Output Compare Register contains an 8-bit value that is continuously compared with the counter value (TCNT0). A match can be used to generate an output compare interrupt, or to generate a waveform output on the OC0 pin.
Those words are from a datasheet. 8-bit value means that it can be written only 0-255 values. So it is crucial to set it properly according to microcontroller clock signal and set prescaler. Prescaler can be set in TCCRx register usually as CSxx bits, but it can differ according to microcontroller type. One more thing what need to be done is to set OCIEx bit in a TIMSK register, that allow CTC Compare Match interrupt to work.
Initialisation
- datasheet checking for informations according microcontroller type
- work mode setting: Normal, PWM Phase Correct, CTC or Fast PWM
- prescaler setting: 0, 8, 64, 256, 1024, external clock source
- OCRx bit setting
- OCIE0 bit setting
- writing a function body as ISR( TIMERx_COMP_vect ) { … }