8-bit AVR Microcontrollers

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.

Figure 1. CTC Mode, Timing Diagram
Note: The “n” in the register and bit names indicates the device number (n = 1, 3, 4 for Timer/Counter 1, 3, 4), 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 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.

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 OCRnA is lower than the current value of TCNTn, 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.

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:


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.