Fast PWM based Muli-color RGB dimming using ATMEGA328 : Induino R5 in C

/*
 * main.c
 */
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>

double dutyCycle = 0;
int colorSet = 0;

int main(void)
{
    DDRB|= 1<<PB4; //testing

    //Timer setting (Fast PWM, non-inverting)
    TCCR0A = (1 << WGM00) | (1 << WGM01) | (1 << COM0A1) | (1 << COM0B1);
    TCCR0B = (1 << CS00);//CLOCK SELECT : set prescaler to 0

    TCCR2A = (1 << WGM20) | (1 << WGM21) | (1 << COM2A1) | (1 << COM2B1);
    TCCR2B = (1 << CS20);//CLOCK SELECT : set prescaler to 0

    DDRD|= 1<<PD6;//Red (OCOA)
    DDRD|= 1<<PD3;//Green (OC2B)
    DDRD|= 1<<PD5;//Blue (OCOB)

    while(1)
    {
      //testing
        PORTB|=1<<PB4;         _delay_ms(30);         dutyCycle+=1;         if(dutyCycle > 100)
        {
            dutyCycle=0;

            //increment colorSet
            colorSet++;
            if(colorSet>6)
            {
              //reset to start color
              colorSet=0;
            }

            //testing
            if( PORTB & (1<<PB4) ) // if PB4 set
                PORTB&=~1<<PB4; //unset it      

            _delay_ms(1000);

        }

        if(colorSet==0)
          setLEDValues(255,0,0); //RED
        else
        if(colorSet==1)
          setLEDValues(0,255,0); //GREEN
        else
        if(colorSet==2)
          setLEDValues(0,0,255); //BLUE
        else
        if(colorSet==3)
          setLEDValues(255,255,255); //WHITE
        else
        if(colorSet==4)
          setLEDValues(0,255,255); //CYAN
        else
        if(colorSet==5)
          setLEDValues(255,0,255); //PINK
        else
        if(colorSet==6)
          setLEDValues(255,255,0); //YELLOW

    }
}

void setLEDValues(int r,int g,int b)
{
    OCR0A = (dutyCycle/100)*r;  //RED led
    OCR2B = (dutyCycle/100)*g;  //GREEN led
    OCR0B = (dutyCycle/100)*b;  //BLUE led
}

/*
 * TCCR0A, TCCR0B - Timer/Counter Control Registers
 * OCOA  , OCOB   - Output Compare Pins
 * OCR0A , OCR0B  - Output Compare Registers
 * CS01           - Clock Select bit
 * COM0A1, COM0B1 - Compare Output Mode bits
 *
 * /
 */

About PraveenMax
My Interests: ------------------ Programming , Drawing & Music

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: