LED Brightness Control Using PWM

Solving Approach:

How do you plan to solve it?

 

 

Code

/*Paste your code here*/
#define F_CPU 16000000UL
#include <avr/io.h>
#include <avr/interrupt.h>

#define PWM_MAX 255

volatile uint16_t accumulator = 0;
volatile uint8_t duty = 0;
volatile uint8_t direction = 0; // 0 = up, 1 = down

// Scaled step values (scaled by 100 for precision)
#define STEP_UP   128   // 255/200 ≈ 1.275 → 1.28 *100
#define STEP_DOWN 255   // 255/100 = 2.55 → 2.55 *100

void pwm_init()
{
    DDRD |= (1 << PD6); // OC0A as output

    // Fast PWM mode, non-inverting
    TCCR0A |= (1 << WGM01) | (1 << WGM00);
    TCCR0A |= (1 << COM0A1);

    // Prescaler 64 → PWM freq ≈ 1kHz
    TCCR0B |= (1 << CS01) | (1 << CS00);

    OCR0A = 0;
}

void timer1_init()
{
    // CTC mode
    TCCR1B |= (1 << WGM12);

    // Prescaler 64
    TCCR1B |= (1 << CS11) | (1 << CS10);

    // 10ms interrupt
    OCR1A = 2499;  // (16MHz / 64) * 0.01 - 1

    TIMSK1 |= (1 << OCIE1A);
}

ISR(TIMER1_COMPA_vect)
{
    if(direction == 0) // Ramp up (2 sec)
    {
        accumulator += STEP_UP;

        while(accumulator >= 100)
        {
            accumulator -= 100;
            if(duty < PWM_MAX)
                duty++;
            else
            {
                direction = 1;
                break;
            }
        }
    }
    else // Ramp down (1 sec)
    {
        accumulator += STEP_DOWN;

        while(accumulator >= 100)
        {
            accumulator -= 100;
            if(duty > 0)
                duty--;
            else
            {
                direction = 0;
                break;
            }
        }
    }

    OCR0A = duty;
}

int main(void)
{
    pwm_init();
    timer1_init();

    sei(); // Enable global interrupts

    while(1)
    {
        // CPU free for other tasks
    }
}



 

Output

Video

Add video of output (know more)

 

 

 

 

 

Photo of Output

Add a photo of your hardware showing the output.

 

 

 

 


 

Upvote
Downvote

Submit Your Solution

Note: Once submitted, your solution goes public, helping others learn from your approach!