Clear Timer on Compare Match (CTC) Mode

In Clear Timer on Compare or CTC mode (WGMn[2:0]=0x2), the OCRnA Register is used to manipulate the counter resolution: the counter is cleared to ZERO when the counter value (TCNTn) matches the OCRnA. The OCRnA defines 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 counting of external events.

The timing diagram for the CTC mode is shown below. The counter value (TCNTn) increases until a compare match occurs between TCNTn and OCRnA, and then counter (TCNTn) 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 OCFnA 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 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 a 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 OCnA 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 (TCCRnA.COMnA[1:0]=0x1). The OCnA 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 fOCn = fclk_I/O/2 when OCRnA is written to 0x00. The waveform frequency is defined by the following equation:

fOCnx=fclk_I/O2N1+OCRnx

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

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