Section 9.3 ATmega328P Output Compare Unit
Each timer/counter on the ATmega328P has two independent output compare units. Each output compare unit allows the timer/counter to trigger timed interrupts and/or generate square waves with differing frequencies and duty cycles. It is also capable of generating pulse-width modulation (PWM) signals.
The output compare unit block diagram is depicted in Figure 9.3.1. The variable
x corresponds to the output compare unit (which could be either A or B). In each output compare unit, the value stored in the timer/counter register TCNTn is continuously compared with the values in an output compare register OCRnx.
Output compare unit A continuously compares the value stored in
TCNTn with the value stored in output compare register A (OCRnA). A match will set the output compare A interrupt flag OCFnA. If interrupts are enabled, this will generate a compare match A interrupt. Depending on the mode of operation configured in the timer/counter control registers (which includes the waveform generation mode WGM bits and compare output mode COM bits), the value stored in OCRnA can be used to modify the value of TOP and generate a waveform on the output compare A (OCnA) pin.
Output compare unit B continuously compares the value stored in
TCNTn with the value stored in output compare register B (OCRnB). A match will set the output compare B interrupt flag OCFnB. If interrupts are enabled, this will generate a compare match B interrupt. Depending on the mode of operation configured in the timer/counter control registers (which includes the waveform generation mode WGM bits and compare output mode COM bits), the value stored in OCRnB can be used to generate a waveform on the output compare B (OCnB) pin.
Each timer/counter interrupt can be enabled by setting the corresponding bits in the timer/counter interrupt mask register (
TIMSKn).
Timer/counters 0 and 1 can additionally be used as trigger sources for the analog to digital converter (ADC). Timer/counter 0 can trigger an ADC conversion on an overflow of the timer/counter (which occurs when the flag
TOV0 is set) or on a compare match between TCNT0 and OCR0A (which occurs when the flag OCF0A is set).
Timer/counter 1 can trigger an ADC conversion on an overflow of the timer/counter (which occurs when the flag
TOV1 is set), on a compare match between TCNT1 and OCR1B (which occurs when the flag OCF1B is set), or when the flag ICF1 is set, which can occur either on an input capture event or on a compare match between TCNT1 and input capture register ICR1 (when ICR1 is used to define TOP).
