19.9.2 Clear Timer on Compare Match (CTC) Mode
In Clear Timer on Compare (CTC) modes (mode 4 or 12, WGMn[3:0]=0x4 or 0xC), the OCRnA or ICRn registers are used to manipulate the counter resolution: the counter is cleared to ZERO when the counter value (TCNTn) matches either the OCRnA (if WGMn[3:0]=0x4) or the ICRn (WGMn[3:0]=0xC). The OCRnA or ICRn define the top value for the counter, hence also its resolution. This mode allows greater control of the compare match output frequency. It simplifies the operation of counting external events.
The timing diagram for the CTC mode is shown below. The counter value (TCNTn) increases until a compare match occurs with either OCRnA or ICRn, and then TCNTn is cleared.
An interrupt can be generated at each time the counter value reaches the TOP value by either using the OCFnA or ICFn flag, depending on the actual CTC mode. If the interrupt is enabled, the interrupt handler routine can be used for updating the TOP value.
In many cases, this feature is not desirable. An alternative will then be to use the Fast PWM mode using OCRnA for defining TOP (WGMn[3:0]=0xF), since the OCRnA then will be double buffered.
For generating a waveform output in CTC mode, the OCnA output can be set to toggle its logical level on each compare match by setting the Compare Output mode bits to toggle mode (COMnA[1:0]=0x1). The OCnA value will not be visible on the port pin unless the data direction for the pin is set to output (DDR_OCnA=1). The waveform generated will have a maximum frequency of fOCnA = fclk_I/O/2 when OCRnA is set to ZERO (0x0000). The waveform frequency is defined by the following equation:
- The “n” indicates the device number (n = 1, 3, 4 for Timer/Counter 1, 3, 4), and the “x” indicates Output Compare unit (A/B).
- N represents the prescaler factor (1, 8, 64, 256, or 1024).
As for the Normal mode of operation, the Timer Counter TOV flag is set in the same timer clock cycle that the counter counts from MAX to 0x0000.