#include <avr/io.h>
#include "lcd.h" 
#include <util/delay.h>



int adc;
int rxd;
int percent;
float volt;
uint8_t charged;


void InitADC()
{
ADMUX=(1<<REFS0);                         // For Aref=AVcc;
ADCSRA=(1<<ADEN)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0); //Prescalar div factor =128
}

uint16_t ReadADC(uint8_t ch)
{
ch=ch&0b00000111;
ADMUX|=ch;
ADCSRA|=(1<<ADSC);
while(!(ADCSRA & (1<<ADIF)));
ADCSRA|=(1<<ADIF);
return(ADC);
}

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);
}

int main()
{

DDRD|=(1<<PB0);
DDRB = 0b00000110; //PB1 charger relay  //PB2 prot relay
PORTB = 0b00000100; //prot on.
PORTC = 0b00000001;  // internal pullup resistor to shut down switch
charged=0;percent=0;


while(1)
{
lcd_init(LCD_DISP_ON);
lcd_clrscr();

LCDWriteIntXY(1,1,percent,2);
LCDWriteIntXY(1,4,"%");


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); // chatger check
if(rxd==0) LCDWriteStringXY(1,9,"AC");

if(volt<23.52)
        {
            //toltes

            charged=0;
            PORTB = 0b00000110; //toltes rele be
            LCDWriteStringXY(1,13,"CH");
        }
else if (volt >= 24)
{
    PORTB = 0b00000100; // toltes rele ki
    LCDWriteStringXY(1,12,"BAT");
    charged=1;
}


percent=100*(volt-21.6)/(24-21.6);

//lcd_puts(“Volts”);
//lcd_gotoxy(8,0);
//lcd_puts(“Amperes”);
//lcd_gotoxy(0,1);

lcd_gotoxy(0,0);
InitADC();
adc=ReadADC(0);
volt=adc*5;
print(adc*5);
lcd_puts("V");
InitADC();
adc=ReadADC(1);
lcd_gotoxy(8,1);
print(adc*10);
lcd_puts("A");
_delay_ms(100);

}
return 0;
}

