#include <avr/io.h>
#include <util/delay.h>
#include <stdlib.h>
#include "lcd.h"
#include "lcd.c"


int adc; //adc ertek
int rxd;	// bemeneti labak ellenorzesehez szukseges valtozo
int percent; // szazalek szamitas eredmenye
float volt,amper; // kiszamolt volt es amper ertek
uint8_t charged; // logikai tiupskent hasznalt valtozo


uint16_t ReadADC(uint8_t ch)
{
ch=ch&0b00000111;
ADMUX|=ch;
ADCSRA|=(1<<ADSC);
while(!(ADCSRA & (1<<ADIF)));
ADCSRA|=(1<<ADIF);
return(ADC);
}
//adc olvasas, elsokent volt, azutan amper meres


void print(uint16_t parameter)
{
parameter%=10000;
lcd_putc((parameter/1000)+48);
parameter%=1000;
lcd_putc((parameter/100)+48);
parameter%=100;
lcd_puts(".");
lcd_putc((parameter/10)+48);
lcd_putc((parameter%10)+48);
} //adc kiiras

int main(void)
{
DDRB|=(0<<PB0); // Portb0 input
PORTB |= _BV(PB0); // internal pullup resistor to shut down switch

DDRB = 0b00000110; //PB1 charger relay  //PB2 prot relay
PORTB = 0b00000100; //prot on.
charged=0;percent=0;

//lcd init
lcd_init(LCD_DISP_ON);
lcd_clrscr();

//adc init 
ADMUX=(1<<REFS0);                         // For Aref=AVcc;
ADCSRA=(1<<ADEN)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0); //Prescalar div factor =128
//ADC init//



while(1)
{


lcd_gotoxy(1,1); lcd_putc(percent);
lcd_gotoxy(4,1); lcd_putc('\037');



rxd = (PINB & 0b00000001); //input check
if(rxd==1) PORTB = 0b00000010; //shutdown by switch
if(volt == 21.6) PORTB = 0b00000010; //shutdown at 0%
rxd = (PIND & 0b00000001); // charger check
if(rxd==1)lcd_gotoxy(9,1); lcd_puts("AC");

if(volt<23.52)
        {
            //toltes

            charged=0;
            PORTB = 0b00000110; //toltes rele be
			lcd_gotoxy(13,1); lcd_puts("CH");
        }
else if (amper == 0)
{
    PORTB = 0b00000100; // toltes rele ki
   lcd_gotoxy(12,1); lcd_puts("BAT");
    charged=1;
}

//lcd_puts(“Volts”);
//lcd_gotoxy(8,0);
//lcd_puts(“Amperes”);
//lcd_gotoxy(0,1);

lcd_gotoxy(0,0);
//


_delay_ms(50);
adc=ReadADC(0);
volt=adc*5;
print(adc*5);
lcd_puts("V");

_delay_ms(50);
adc=ReadADC(1);
lcd_gotoxy(8,1);
amper=adc*10;
print(adc*10);
lcd_puts("A");
_delay_ms(10);
percent=100*(volt-21.6)/(24-21.6);
_delay_ms(100);

}
}

