Output Compare Mode

The output compare mode is used by the microcontroller to produce output signals. The outputs may be square or asymmetrical waves, and they may be varying in frequency or symmetry. In the output compare mode the program loads a value in the output compare register (OCR1xH and OCR1xL)This value is compared to the value in the timer/counter register (TCNT1H and TCNT1L) , and when the two values match an interrupt occurs. This interrupt triggers the processor to execute a piece of program.The output compare mode can also automatically set, clear, or toggle a specific output port pin.

The output compare modes for TIMER1 are controlled by timer counter control register TCCR1A.

COM1A0 & COM1A1 Control the compare mode function for compare resister A
COM1B0 & COM1B1 Control the compare mode function for compare resister B

Control Bit Definitions TCCR1A
COM1x1 COM1x0 Function (x = A or B)
0 0 no output
0 1 Compare match toggles the OC1x line
1 0 Compare match clears the OC1x line to 0
1 1 Compare match sets the OC1x line to 1

As shown in the table, the compare mode control bits determine what action will be taken when a match occurs between the output compare register (OCR1xH and OCR1xL) and the timer register (TCNT1H and TCNT1L) . The associated output pin (OC1x) can be left alone, toggled, set, or cleared. The match also generates an interrupt. The purpose of the program code of the interrupt service routine is to reset or reload the compare register for the next match that must occur.

In this example we want to generate a square wave of 10kHz. Below you can see the schematic.

 So we need to calculate the value for the reload of the output compare register OCR1xH and OCR1xL.

One half of the square wave is 50µs.

The clock interval is 16Mhz / 8 = 2000kHz = 0,5µs

50µs / 0,5µs = 100 clock pulses per match point, we can program this in the Interrupt Service Routine. Below is the complete code.

// program name: TIMER1_OCM
// date: 04.09.2015
// author: www.avrprojects.net
// target device: atmega328
// harware: ATMEGA326 board output compare mode
// software: WinAVR-20100110 compiler
#include <avr/io.h> #include <util/delay.h> #include <avr/interrupt.h> #include <util/lcd.h>
/* Timer 1 output compare A interrupt service routine*/
OCR1A = OCR1A + 100;
} int main (void)
DDRB=0b00000010;/* set OC1A bit for output */
TCCR1A=0x40; /* enable output compare mode to toggle OC1A pin on match */
TCCR1B=0x02; /*set prescaler to Clock/8*/
TIMSK=0x10; /* unmask output compare match interrupt for register A */
sei(); /* enable global interupt */ while(1) { ;/* do nothing*/ }

In this picture you see the result of the code meusured on the Output Compare Pin.

output compare mode