PWM on RGB led using ATMEGA328 : Induino – R5

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

double dutyCycle = 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);


        //PWM - RED
  
        dutyCycle+=1;
  
        if(dutyCycle > 100)
        {
          dutyCycle=0;
            
          if( PORTB & (1<<PB4) ) // if PB4 set
              PORTB&=~1<<PB4; //unset it      
              
          _delay_ms(500);
  
        }
        OCR0A = (dutyCycle/100)*255;  //RED led
        OCR0B = (dutyCycle/100)*255;  //BLUE led
        OCR2B = (dutyCycle/100)*255;  //GREEN 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: