#define F_CPU 8000000UL
#include <util/delay.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <avr/pgmspace.h>
#include <avr/eeprom.h>

#include "lcd.h"
#include "SI484x.h"

  char lcd_buffer[8], conf_buf[2];
  char ee_buf[] EEMEM = {1,2};
  char eepr;



void lcd_udate(void)
{
	sprintf(lcd_buffer,"%2x%2x",si_buf[2],si_buf[3]);
	if(lcd_buffer[2] == 0x20) lcd_buffer[2] = 0x30;
	lcd_buffer[4] = lcd_buffer[3];
	lcd_buffer[3] = 0x2E; //точка
	lcd_clrscr();
	lcd_gotoxy(0,0); //идем в нулевую точку
	lcd_puts(lcd_buffer);
	lcd_puts("MHz");
	lcd_gotoxy(0,1);
	lcd_puts("Band ");
	sprintf(lcd_buffer, "%u %u", conf_buf[0], conf_buf[1]/10);
	lcd_puts(lcd_buffer);
}

ISR(INT0_vect)
{
	GICR = 0x00;  
	si484x_red();
	lcd_udate();
	GICR = 0x40;         
} 
 
 
 
int main(void)
{  
	lcd_init(LCD_DISP_ON);	
	si484x_int();
	sei();
	eepr = 0;
	eeprom_read_block(&conf_buf[0], &ee_buf[0], sizeof(conf_buf));

	if ((conf_buf[0] < 1) || (conf_buf[0] > 2) || (conf_buf[1] < 3) || (conf_buf[1] > 63))
	{
		conf_buf[0] = 1;
		conf_buf[1] = 0x30;
	}

	si484x_band(conf_buf[0]);
	_delay_ms(50);
	si484x_vol(conf_buf[1]);
	_delay_ms(50);

	while(1)
	{ 
		if ((PIND & (1 << PD5)) == 0)
		{ 
			_delay_ms(5); 
			if ((PIND & (1 << PD5)) == 0)
			{
				if(conf_buf[1] > 3)
				{  
					conf_buf[1] = conf_buf[1] - 5;
					si484x_vol(conf_buf[1]);
				}	
			}
			while((PIND & (1 << PD5)) == 0){}
			eepr = 1;
			_delay_ms(10);
		}  
	   
		if ((PIND & (1 << PD3)) == 0)
		{ 
		   _delay_ms(5); 
		   if ((PIND & (1 << PD3)) == 0)
		   {
				if(conf_buf[1] < 63)
				{
					conf_buf[1] = conf_buf[1] + 5;
					si484x_vol(conf_buf[1]);
				}
		   }
		   while((PIND & (1 << PD3)) == 0){}
		   eepr = 1;
		   _delay_ms(10);
		}   
     
		if ((PIND&(1 << PD7)) == 0)
		{ 
		   _delay_ms(5); 
		   if ((PIND&(1 << PD7)) == 0)
		   {
				if(conf_buf[0] == 1)
				{
					conf_buf[0] = 2; 
					si484x_band(conf_buf[0]);
				}
				else
				{
					conf_buf[0] = 1; 
					si484x_band(conf_buf[0]);
				}
		   }
		   while((PIND&(1 << PD7)) == 0){}
		   eepr = 1;
		   _delay_ms(10);
		}   
     
		if (eepr == 1)
		{ 
			GICR = 0x00;
			eepr = 0;
            lcd_udate();
			eeprom_write_block(&conf_buf[0], &ee_buf[0], sizeof(conf_buf));
			GICR = 0x40; 
		} 
    }
} 
 
