8-bit AVR Microcontrollers

Output Compare Units

The 16-bit comparator continuously compares TCNTn with the Output Compare Register (OCRnx). If TCNT equals OCRnx the comparator signals a match. A match will set the Output Compare Flag (TIFRn.OCFx) at the next timer clock cycle. If enabled (TIMSKn.OCIEx = 1), the output compare flag generates an output compare interrupt. The OCFx is automatically cleared when the interrupt is executed. Alternatively, the OCFx can be cleared by software by writing a logical one to its I/O bit location. The waveform generator uses the match signal to generate an output according to operating mode set by the Waveform Generation mode (WGMn[3:0]) bits and Compare Output mode (COMnx[1:0]) bits. The TOP and BOTTOM signals are used by the waveform generator for handling the special cases of the extreme values in some modes of operation, see Modes of Operation.

A special feature of output compare unit A allows it to define the Timer/Counter TOP value (i.e., counter resolution). In addition to the counter resolution, the TOP value defines the period time for waveforms generated by the waveform generator.

Below is a block diagram of the output compare unit. The elements of the block diagram that are not directly a part of the output compare unit are gray shaded.

Figure 1. Output Compare Unit, Block 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).

The OCRnx is double buffered when using any of the twelve Pulse Width Modulation (PWM) modes. For the Normal and Clear Timer on Compare (CTC) modes of operation, the double buffering is disabled. The double buffering synchronizes the update of the OCRnx to either TOP or BOTTOM of the counting sequence. The synchronization prevents the occurrence of odd-length, non-symmetrical PWM pulses, thereby making the output glitch-free.

When double buffering is enabled, the CPU has access to the OCRnx Buffer register. When double buffering is disabled, the CPU will access the OCRnx directly.

The content of the OCRnx (Buffer or Compare) register is only changed by a write operation (the Timer/Counter does not update this register automatically as the TCNTn and ICRn). Therefore OCRnx is not read via the high byte temporary register (TEMP). However, it is good practice to read the low byte first as when accessing other 16-bit registers. Writing the OCRnx must be done via the TEMP register since the compare of all 16 bits is done continuously. The high byte (OCRnxH) has to be written first. When the high byte I/O location is written by the CPU, the TEMP register will be updated by the value written. Then when the low byte (OCRnxL) is written to the lower eight bits, the high byte will be copied into the upper 8-bits of either the OCRnx buffer or OCRnx in the same system clock cycle.