#ifndef F_CPU
#define	F_CPU	1000000UL
#error asdf
#endif

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

#include "lcd.h"

#define BAUDRATE 38400
#define BRR	(F_CPU/16/BAUDRATE-1)

#define start_counter()	\
	do{	\
		TCNT1 = 0;	\
		TCCR1B = _BV(CS12) | _BV(CS11) | _BV(CS11); \
	}while(0);

#define stop_counter() TCCR1B = 0;

#define start_timer()	\
	do{	\
		TCNT0 = 0;	\
		SFIOR |= _BV(PSR10);	\
		TCCR0 = _BV(CS02) | _BV(CS00);\
	}while(0);

#define stop_timer() TCCR0 = 0;



char hello[] = {0xAB, 0x61, 0x63, 0xbf, 0x6f, 0xbf, 0x6f, 0xbc, 0x65, 0x70, 0};

volatile uint8_t flags = 0;;

static delay_ms(uint8_t ms)
{
	while(ms--)
	{
		_delay_ms(1);
	}
}

static void init_all()
{
	uint16_t i;
//	UBRRH = (unsigned char)(BRR>>8);
//	UBRRL = (unsigned char)(BRR);
//	UCSRB = _BV(TXEN) | _BV(RXEN);
//	UCSRC = _BV(URSEL) | _BV(USBS) | _BV(UCSZ0)| _BV(UCSZ1);
//	DDRD = 4;
//	UDR = 'a';
	lcd_init();
//	UDR = 'b';
	lcd_str(hello);
	lcd_gotoxy(0,1);
//	UDR = 'c';
	delay_ms(200);
//	UDR = 'd';
	
	TIMSK |= _BV(TOIE0);
	sei();
}

ISR(TIMER0_OVF_vect)
{
	static uint8_t count = 0;

	if(++count==38)
	{
		stop_counter();
		stop_timer();
		count = 0;
		PORTD &= ~_BV(PD2);
		flags |= 1;

	}
}

int main()
{
	uint8_t i;
	char ch = '0',c;
	char buffer[16];
	init_all();
	while(1)
	{
		start_counter();
		start_timer();
		PORTD |= _BV(PD2);
		while(!(flags&1));
		flags &= ~1;
		lcd_gotoxy(0,1);
		sprintf(buffer,"freq %d      ", TCNT1);
		lcd_str(buffer);
	}
}
