//
// 16-bit Fast PWM
//

#define F_CPU 1000000

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

// Pins
#define PIN_POT			PA1
#define PIN_TEST		PA0
#define PIN_SW_START		PA4
#define PIN_SW_DOWN		PA5
#define PIN_SW_UP		PA3
#define PIN_PWM			PA6
#define PIN_LED1		PB0
#define PIN_LED2		PB1
#define PIN_LED3		PB2
#define PIN_LED4		PA7

// Main
int main(void)
{
	PORTA = _BV(PIN_TEST) | _BV(PIN_POT) | _BV(PIN_SW_START) | _BV(PIN_SW_DOWN) | _BV(PIN_SW_UP);	// Pull-up
	DDRA = _BV(PIN_PWM) | _BV(PIN_LED4) | _BV(PA2);	// Output A
	PORTB = 0x00;	// No pull-up
	DDRB = _BV(PIN_LED1) | _BV(PIN_LED2) | _BV(PIN_LED3);	// Output B

	// Power Reduction
	PRR = _BV(PRTIM0) | _BV(PRUSI) | _BV(PRADC);

	// Test PWM
	TCCR1A = _BV(COM1A1) | _BV(WGM11);
	TCCR1B = _BV(WGM13) | _BV(WGM12) | _BV(CS10);
	OCR1A = 1500;	// High = 1.5ms
	ICR1 = 20000;	// Period = 20ms


	while(1)
	{
		if(!(PINA & _BV(PIN_SW_DOWN)))
		{
			if(OCR1A > 1000)
			{
				OCR1A--;
			}
		}
		else if(!(PINA & _BV(PIN_SW_UP)))
		{
			if(OCR1A < 2000)
			{
				OCR1A++;
			}
		}

		_delay_ms(10);
	}

	return 1;
}
