Fast PWM using Two PWM Channels

Created on: 7 May 2013

Part 12 of the ATtiny2313 Tutorial

Timer/Counter0 of the ATtiny2313 is used to generate PWM to dim two LEDs using two PWM channels. The timer/counter is used in fast PWM mode.

Fast PWM Circuit Diagram

The circuit diagram shows LEDs connected to PB2 (OC0A PWM channel from TC0) and PD5 (OC0B PWM channel from TC0).

Fast PWM circuit diagram
Circuit Diagram for the Dual Channel Fast PWM Example

Fast PWM Software

The C source code controlling two PWM channels from timer/counter0 in fast PWM mode is shown here.

// TC0_fast_PWM.c
#define F_CPU 1000000UL
#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
    unsigned char PWM_val1 = 0;		// 8-bit PWM value
    unsigned char PWM_val2 = 255;	// 8-bit PWM value
    unsigned char up_dn = 0;		// up down count flag
    
    DDRB   |= (1 << PB2);                   // PWM output on PB2 - OC0A 
    DDRD   |= (1 << PD5);                   // PWM output on PD5 - OC0B
    // fast PWM mode
    TCCR0A = (1 << COM0A1) | (1 << COM0B1) | (1 << WGM01) | (1 << WGM00);
    TCCR0B = (1 << CS01);   // clock source = CLK/8, start PWM
    
    while(1)
    {
        if ((PWM_val1 == 255) || (PWM_val1 == 0)) {
            up_dn ^= 0x01;      // toggle count direction flag
        }
        _delay_ms(5);
        OCR0A  = PWM_val1;       // write new PWM value
        OCR0B  = PWM_val2;
        if (up_dn) {            // increment or decrement PWM value
        PWM_val1++;
        PWM_val2--;
    }
    else {
        PWM_val1--;
        PWM_val2++;
    }
    }
}

This example is very similar to the code used in the second example of the previous part of this tutorial, except an extra output (second PWM channel) is enabled on PD5. The PWM is now initialized into fast PWM mode and the second PWM channel is enabled.

When the value continuously written to one PWM channel is incremented to brighten the attached LED, the value written to the other channel is decremented to dim the attached LED.

Project Source Code

The above code can be copied and pasted into your own project, or download the Atmel Studio project for this example here:

TC0_fast_PWM.zip (15.6kB)