Starting Electronics Needs Your Help!
It is that time of the year when we need to pay for web hosting and buy new components and equipment for new tutorials. You can help by making a donation. Contribute to this website by clicking the Donate button. The total will be updated once daily. (You may need to clear your browser cache to see the updates.)

Target Amount: $2000
Amount Raised: $1369

Donations Received

Top Donor: C.C. $100

X

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.

This video shows two LEDs being brightened and dimmed alternately. Each LED is controlled by a separate PWM output from timer/counter0.

Can't see the video? View on YouTube →

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)

Amazon.com

Amazon.co.uk

← Go back to Part 11Go to Part 13 →