17.12.2 Clear Timer on Compare Match (CTC) Mode

In Clear Timer on Compare or CTC modes (mode 4 or 12, WGM0[3:0]=0x4 or 0xC), the OCR0A or ICR0 registers are used to manipulate the counter resolution: the counter is cleared to ZERO when the counter value (TCNT0) matches either the OCR0A (if WGM0[3:0]=0x4) or the ICR0 (WGM0[3:0]=0xC). The OCR0A or ICR0 define the top value for the counter, hence also its resolution. This mode allows greater control of the compare match output frequency. It also simplifies the operation of counting external events.

The timing diagram for the CTC mode is shown below. The counter value (TCNT0) increases until a compare match occurs with either OCR0A or ICR0, and then TCNT0 is cleared.

Figure 17-8. CTC Mode, Timing Diagram
Note: The “n” in the register and bit names indicates the device number (n = 0 for Timer/Counter 0), and the “x” indicates Output Compare unit (A/B).

An interrupt can be generated at each time the counter value reaches the TOP value by either using the OCF0A or ICF0 Flag, depending on the actual CTC mode. If the interrupt is enabled, the interrupt handler routine can be used for updating the TOP value.

Note: Changing TOP to a value close to BOTTOM while the counter is running must be done with care, since the CTC mode does not provide double buffering. If the new value written to OCR0A is lower than the current value of TCNT0, the counter will miss the compare match. The counter will then count to its maximum value (0xFF for a 8-bit counter, 0xFFFF for a 16-bit counter) and wrap around starting at 0x00 before the compare match will occur.

In many cases this feature is not desirable. An alternative will then be to use the Fast PWM mode using OCR0A for defining TOP (WGM0[3:0]=0xF), since the OCR0A then will be double buffered.

For generating a waveform output in CTC mode, the OC0A output can be set to toggle its logical level on each compare match by setting the Compare Output mode bits to toggle mode (COM0A[1:0]=0x1). The OC0A value will not be visible on the port pin unless the data direction for the pin is set to output (DDR_OC0A=1). The waveform generated will have a maximum frequency of fOC0A = fclk_I/O/2 when OCR0A is set to ZERO (0x0000). The waveform frequency is defined by the following equation:

f OCnA = f clk_I/O 2 N 1 + OCRnA
Note:
  • The “n” indicates the device number (n = 0 for Timer/Counter 0), 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.