#include <avr/io.h>
#include <avr/wdt.h>
#include <avr/interrupt.h>

volatile unsigned int	ticled, ticpwm;
volatile int8_t smer = 1;   // +1 = hore, -1 = dole

#define BOTTOM	6			//4ms		PWM 250 úrovní
#define PERIODA	4			//ms
#define TOP		255

//------------------------------------------------------------------------------
ISR (TIMER0_OVF_vect)				//Obsluha prerusenia TCO
{	
	ticled++; ticpwm++;
	PORTD ^= (1<<PORTD7);			//test osciloskop	
	if (ticled >= (1000 / PERIODA))		{ticled = 0;}
	if (ticled < (50 / PERIODA))		{PORTB |= (1 << PORTB5);}
	else if (ticled < (250 / PERIODA))	{PORTB &= ~(1 << PORTB5);}
	else if (ticled < (300 / PERIODA))	{PORTB |= (1 << PORTB5);}
	else {PORTB &= ~(1 << PORTB5);}
	
	if (ticpwm >= (12/PERIODA)) {
		ticpwm = 0;
		if (OCR0B >= TOP)		smer = -1;
		if (OCR0B <= BOTTOM+1)  smer = 1;
			
		OCR0A += smer;
		OCR0B += smer;
	}
	TCNT0 = BOTTOM;	
}
//------------------------------------------------------------------------------
int main (void) {
	
	wdt_enable(WDTO_500MS);				//povolenie WDT 0,5sec
	DDRB |= (1<<DDB5);					//nastavenie LED na vystup 
	DDRD |= (1<<DDD6)|(1<<DDD5);		//Nastavenie OCR0A, OCR0B na vystup
	DDRD |= (1<<DDD7);					//nastavenie vystup pre osciloskop
		
	//TC0 - normal mode,
	TCCR0B |= (1<<CS02);				//set prescaler to 256 (Timer clock = system clock/256)
	TIFR0 |= 1<<TOV0;					//Clear TOV0 flag
	TIMSK0 |= 1<<TOIE0;	  				//Enable Timer0 overflow interrupt
	TCNT0 = BOTTOM;						//Nastavenie TCNT0 
	//TC0 - Fast PWM
	TCCR0A |= (1<<WGM01)|(1<<WGM00);		//set fast PWM (TOP=0xFF)
	TCCR0A |= (1<<COM0A1);					//set non-inverting mode OCR0A (PD6)
	//TCCR0A |= (1<<COM0A1)|(1<<COM0A0);	//set inverting mode OCR0A (PD6)
	TCCR0A |= (1<<COM0B1)|(1<<COM0B0);		//set inverting mode OCR0B (PD5)
	//TCCR0A |= (1<<COM0B1);				//set non-inverting mode OCR0B (PD5)
	OCR0A = BOTTOM;
	OCR0B = BOTTOM;
	sei();
	
	while(1) { 
		wdt_reset();
	}
}
//------------------------------------------------------------------------------

