29 lines
672 B
C
29 lines
672 B
C
#include "pwm.h"
|
|
|
|
void pwm_init(void)
|
|
{
|
|
// initialize timer 1 for PWM
|
|
TCCR1A = (1<<WGM11) | (1<<COM1A1);
|
|
TCCR1B = (1<<WGM13) | (1<<WGM12) | (1<<CS11);
|
|
OCR1A = 0;
|
|
// set PWM pin as output
|
|
DDRB |= (1<<PB1);
|
|
}
|
|
|
|
void pwm_set_frequency(float frequency)
|
|
{
|
|
// calculate timer 1 TOP value
|
|
uint16_t top = (uint16_t)(PWM_MAX_FREQ / frequency);
|
|
top = (top > 0xffff) ? 0xffff : top;
|
|
// set timer 1 TOP value
|
|
ICR1 = top;
|
|
}
|
|
|
|
void pwm_set_duty_cycle(float duty_cycle)
|
|
{
|
|
// calculate OCR1A value from duty cycle
|
|
uint16_t ocr = (uint16_t)(duty_cycle * ICR1);
|
|
ocr = (ocr > ICR1) ? ICR1 : ocr;
|
|
// set OCR1A value
|
|
OCR1A = ocr;
|
|
} |