Clear Timer on Compare Match (CTC) Mode

In Clear Timer on Compare (CTC) mode (WGM0[2:0]=0x2), the OCR0A register is used to manipulate the counter resolution: the counter is cleared to ZERO when the counter value (TCNT0) matches the OCR0A. The OCR0A defines the top value for the counter, hence its resolution. This mode allows greater control of the compare match output frequency. It also simplifies the counting of external events.

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

Figure 1. CTC Mode, Timing Diagram

An interrupt can be generated each time the counter value reaches the TOP value by setting the OCF0A flag. 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 an 8-bit counter, 0xFFFF for a 16-bit counter) and wrap around starting at 0x00 before the compare match will occur.

For generating a waveform output in CTC mode, the OC0A output can be set to toggle its logical level on each compare match by writing the two least significant Compare Output mode bits in the Timer/Counter Control Register A Control to toggle mode (TCCR0A.COM0A[1:0]=0x1). The OC0A value will only be visible on the port pin unless the data direction for the pin is set to output. The waveform generated will have a maximum frequency of fOC0 = fclk_I/O/2 when OCR0A is written to 0x00. The waveform frequency is defined by the following equation:


N represents the prescaler factor (1, 8, 64, 256, or 1024).

As for the Normal mode of operation, the Timer/Counter Overflow flag TOV0 is set in the same clock cycle that the counter wraps from MAX to 0x00.