20.7.2 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.
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.
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:
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.