//
// PWM with PLL Example
// By PEK '2006
//
// Compiler: GCC
// MCU: ATTiny26
// Clock: Internal PLL/4 = 16MHz
//

#define F_CPU 16000000

#include <avr/io.h>

// Definition of functions
#define STOP_PWM() (TCCR1B = 0x00)
#define START_PWM() (TCCR1B = _BV(CS10))
#define SET_PWM(value) (OCR1B = value)

// Main
int main(void)
{
	uint8_t uInput = 0;

	// Setup Ports
	PORTA = 0xFF;
	DDRA = 0x00;	// PortA as input
	PORTB = 0b11110111;
	DDRB = 0b00001000;	// OC1B as output

	// Setup PLL
	PLLCSR = _BV(PLLE);	// Enable PLL
	while(!(PLLCSR & _BV(PLOCK)));	// Wait for PLL to lock
	PLLCSR |= _BV(PCKE);	// Change the timer1 clock source to the PLL (64 MHz)

	// Setup Timer1 & PWM
	TCCR1A = _BV(COM1B1) | _BV(PWM1B);	// OC1B cleared on compare match, PWMB enabled
	SET_PWM(0x00);	// PWM compare register (0x00 = PWM signal low)
	OCR1C = 0xFF;	// PWM frequency set to 250 kHz (64MHz/(255+1)), give us resolution of 8 bits
	START_PWM();

	while(1)
	{
		if(PINA != uInput)	// New value on PortA?
		{
			uInput = PINA;

			SET_PWM(uInput);	// Set new duty of PWM
		}
	}

	return 1;
}

