#include <stdio.h>
#include <avr/io.h>

/*
 * UART-Initialization from www.mikrocontroller.net
 * Hint: They are awesome! :-)
 */

#ifndef F_CPU
#warning "F_CPU was not defined, defining it now as 16000000"
#define F_CPU 16000000UL
#endif

#define BAUD 9600UL      // baud rate
// Calculations
#define UBRR_VAL ((F_CPU+BAUD*8)/(BAUD*16)-1)   // smart rounding
#define BAUD_REAL (F_CPU/(16*(UBRR_VAL+1)))     // real baud rate
#define BAUD_ERROR ((BAUD_REAL*1000)/BAUD) // error in parts per mill, 1000 = no error

#if ((BAUD_ERROR<990) || (BAUD_ERROR>1010))
  #error Error in baud rate greater than 1%!
#endif


void uart_init(void)
{
    UBRR0H = UBRR_VAL >> 8;
    UBRR0L = UBRR_VAL & 0xFF;

    UCSR0C = (0<<UMSEL01)|(0<<UMSEL00)|(1<<UCSZ01)|(1<<UCSZ00);  // asynchron 8N1
    UCSR0B |= (1<<RXEN0); // enable UART RX
}

/* Receive symbol */
uint8_t uart_getc(void)
{
    while (!(UCSR0A & (1<<RXC0)))   // wait until symbol is ready
        ;
    return UDR0;                    // return symbol
}

void pwm_init(void){
	TCCR2A = (1<<COM2B1)|(1<<COM2B0)|(1<<WGM21)|(1<<WGM20)|(0<<CS22)|(0<<CS21)|(1<<CS20);
	TCCR2B |= (0<<CS22)|(0<<CS21)|(1<<CS20);
	OCR2B=128;
}


void initIO(void)
{
	DDRD |= (1<<DDD3);
    DDRB = 0xff;
}

#define LED PB5 // LED is on Pin 13 or Pin 5 of Port B

int main(void)
{
  initIO();
  uart_init();
  pwm_init();
  while (1)
  {
    uint8_t c;
    c = uart_getc();

    if((c & 0x01) == 0)
    	PORTB &= ~(1<<LED); // clear
    else
    	PORTB |= (1<<LED); // set

	OCR2B = ~c;
  }
  return 0; // never reached
}


