2 Timer Event Notification
The timer operates independently of the program execution. For each timer event there is a corresponding status flag in the Timer Interrupt Flag Register (TIFRn). The occurrence of timer events require a notification of the processor to trigger the execution of corresponding actions. This is done by setting the status flag of the event which occurred.
- Constantly polling of status flags – interrupt flags and execution of corresponding code.
- Break of program flow and execution of Interrupt Service Routines (ISR).
- Changing the level of output pins automatically.
Polling of Interrupt Flags
This method makes use of the fact that the processor marks the timer events by setting the corresponding interrupt flags. The main program can frequently check the status of these flags to see if one of these events occurred. This requires some program overhead, which will cost additional processing time. The advantage of this solution is the very short response time when tight loops are used.
loop: ; Label
lds r16,TIFRn ; Load TIFRn in
sbrs r16,TOV0 ; Skip next instruction if bit (zero) in register
; (r16) is set
rjmp loop ; Jump to loop
; Event Service Code starts here
Interrupt Controlled Notification
The AVR can be configured to execute interrupts if a timer event has occurred (the corresponding interrupt flag in the TIFRn is set). Normal program execution will be interrupted (almost) immediately and the processor will execute the code of the Interrupt Service Routine. The advantage compared to polling of interrupt flags is zero overhead in the main loop. This saves processing time. The section Setting Up the Timers shows a few examples of how this can be implemented.
ldi r16,1<<OCIE2A
sts TIMSK2,r16 ; Enable timer output compare interrupt
sei ; Enable global interrupts
Automatic Reaction on Events
Timers on this device support the possibility to react on timer interrupt events on purely hardware basis without the need to execute code. Related output pins can be configured to be set, cleared, or toggled automatically on a compare match. In contrast to the two other solutions this happens in parallel to normal code execution and requires no processing time.
ldi r16, (1<<COM2A1)|(1<<WGM21)|(1<<WGM20)
sts TCCR2A,r16 ; OC2A toggling on compare match/timer
; Clock = system clock
ldi r16,32
sts OCR2A,r16 ; Set output compare value to 32
To
enable pin toggling, the data direction register bit corresponding to OCx has to be set
to make it an output pin.