5.1 Example 4 : Timer2 PWM Generation

This example shows how to generate voltages between VCC and GND at the output pin of the PWM (PB3/OC2A). To observe this, PB3 should be connected an LED. This PWM output signal has a duty relation of 1/8 to 7/8 (OCR2A = 0xE0).

The following initialization routine shows how to set up such a system:
init_Ex4:
	; 8 bit PWM non-inverted
	ldi r16, (1<<COM2A1)|(1<<WGM21)|(1<<WGM20);
	sts TCCR2A,r16 ; 8 bit PWM non-inverted
	ldi r16,(1<<CS20) 
	sts TCCR2B,r16 ; Timer clock = I/O clock
	ldi r16,0xE0
	sts OCR2A,r16 ; Set compare value/duty cycle ratio
	sbi DDRB, PORTB3 ; Set OC2A pin as output
	ret

The corresponding C code looks like this:
void init_Ex4(void)
{
	/* Enable non inverting 8-Bit PWM */
	TCCR2A = (1<<COM2A1)|(1<<WGM21)|(1<<WGM20);
	/* Timer clock = I/O clock */
	TCCR2B = (1<<CS20);
	/* Set the compare value to control duty cycle */
	OCR2A  = 0xE0;
	/* Enable Timer 2 Output Compare Match Interrupt */
	TIMSK2 = (1 << OCIE2A);
	/* Set OC2A pin as output */
	DDRB |= (1 << 	OC2A_PIN);
}