Friday 4 May 2012

Some C code for PWM

Simple PWM Project

/*
 * Simple_PWM.c
 *
 * Created: 10/04/2012 8:13:17 PM
 * 
 * PINC pins 0 and 1 for duty select, via dip switch
 */

#include <avr/io.h>

#include <stdint.h>
#include "timer.h"
#include "global.h"

#define PWM_select (PINC & 3)


int main(void)
{
    const uint8_t resolution = 8;
    uint8_t old_sw;        // stores previous switch status
   
    // set up ports
    DDRD = 0x20;        // set OC1A (PWM) out
    PORTC = 0x03;        // set pull up resistors for pwm dsw select
    // timer1 settings
    timer1Init();        // init timer1 vis timer lib
    timer1PWMInit(resolution);  // init PWM
    timer1PWMAOn();        // turn on PWM
   
    sei();
   
    while(1)
    {
        if(PWM_select != old_sw){
            old_sw = PWM_select;
            switch (PWM_select)
            {
            case 0: timer1PWMASet(dutyCyclePercent(5,resolution));    // 5% duty
                break;
            case 1:    timer1PWMASet(dutyCyclePercent(30,resolution));    // 30% duty
                break;
            case 2: timer1PWMASet(dutyCyclePercent(60,resolution));    // etc
                break;
            case 3:    timer1PWMASet(dutyCyclePercent(95,resolution));
                break;
            default:
            break;
            }
        }
    }
}