// Wiring:
//A3 - rezerv
//A1 - Volts (solar)
//A5 - Volts (battery)
//A2 - Amps (solar)
//A7 - Amps (battery)

//D4---LEFT
//D5---RIGHT
//D7---SELECT
 
//D3----PWM out to DCOI

//D12---LCD_RST (1)
//D11---LCD_CE (2)
//D10---LCD_DC (3)
//D9----LCD_DIN (4)
//D8----LCD_CLK (5)
//3,3v--LCD_VCC (6)
//D6----LCD_LIGHT (7) PWM out
//------LCD_GND (8)

//// DS1302:  SDA pin   -> Arduino Digital 4
//            SCL pin   -> Arduino Digital 5


#define LCD_C     LOW
#define LCD_D     HIGH

#define PIN_RESET 12
#define PIN_SCE   11
#define PIN_DC    10
#define PIN_SDIN  9
#define PIN_SCLK  8
/////////////////////////////////////////////////////////////
#define ONE_WIRE_BUS 2// Подключение цифрового вывода датчика к 10-му пину Ардуино.
//#define ONE_WIRE_BUS_2 5// Подключение цифрового вывода датчика к 8-му пину Ардуино.
/////////////////////////////////////////////////////////////
#define DS1307_I2C_ADDRESS 0x68
#define DS1307_RAM ramBuffer

////////////////////////////////////


//#include <stdlib.h>;
#include <Wire.h>
#include <avrasm.h>
#include "header.h";
#include <PWM.h>
#include <EEPROM2.h>
#include <DS1307.h>
/////////////////////////////////////////////////////////////
#include <OneWire.h>// Инициализация библиотеки шины OneWire.
#include <DallasTemperature.h>// Инициализация библиотеки термодатчиков.
//#include <EEPROM.h>
/////////////////////////////////////////////////////////////
#include <LCD5110_Graph.h>
LCD5110 myGLCD(8,9,10,12,11);
extern uint8_t SmallFont[];
///////////////////////////////////////////////////

int32_t frequency = 15000; //frequency (in Hz)

///////////////////////////////////////////////////////
// Init the DS1307
DS1307 rtc(A4, A5);
/////////////////////////////////////////////////////////////////////
Time t;
Time t2;

//////////////////////////////////////////////////////
float panelVolts = 0;
float batteryVolts = 0;
float lastPanelVolts = 0;
float lastBatteryVolts = 0;
float batteryVolts_2 = 0;
float lastPanelVolts_2 = 0;
float lastBatteryVolts_2 = 0;
float panelAmps = 0;
float lastPanelAmps = 0;
float batteryAmps = 0;
float lastBatteryAmps = 0;
float efficiency = 0;
//float siemens = 0;
float panelWatts = 0;
float lastPanelWatts = 0;
float lastPanelWatts2 = 0;
float batteryWatts = 0;
float maxwatts = 0;
float maxpwmwatts = 1;
float maxpwmwatts2 = 1;
//float lastmaxpwmwatts = 0;
float Umenu = 0;
float Voc = 0;
float Isc = 0;
float tmp1 = 0;
float tmp2 = 0;
float tmp3 = 0;
float Umax2 = 14.2;
float Umax1 = 13.8;
float Umin = 12.8;
float Umain = 13.8;
float Umin_2 = 11.5;
float Umax_2 = 14.2;
float sumwatsday = 0;
float sumwats = 0;
float floatbyte = 0;
/////////////////////////////////
float T1; // DallasTemperature1
float T2; //DallasTemperature
float T3 = 0; //задержка опроса DallasTemperature
////////////////////////////////

char tmp[25];
boolean highWatts = false;
int chartX = 0;
int chartY = 0;
boolean mpptOn = false;
const boolean initialise = true;
int barwatts = 0;
///////////////////////////////////////////////////////////////////
int sensorValue = 0;
//int al =11;
int a = 0; 
int b = 0;
int c = 3;
int m = 1; 
int n = 1;
int men = 0;
int men2 = 0;
int tmen = 0;
int b_type;
int b_type_n;
int b_type_c;
int time = 0;
int sek = 0;
int sek2 = 0;
int has = 0;
int mi = 0;
int den = 1;
int mec = 1;
int god = 2010;
int mi2 = 0;
//int den2 = 1;
int adress = 0;
//byte sumwatsday1 = 0;
//byte sumwatsday2 = 0;
//byte sumwats1 = 0;
//byte sumwats2 = 0;
byte byte1 =0;
byte byte2 =0;
byte byte3 =0;
byte byte4 =0;

//////////////////////////////////////////////////////////////////
int brightness = 75;       // яркость LED, начинаем с половины
int fadeAmount = 5;        // шаг изменения яркости LED
unsigned long currentTime;
unsigned long loopTime;
const int pin_LEFT = 4;       // pin 4 
const int pin_RIGHT = 5;       // pin 5 
const int pin_SELECT = 7;       // pin 7
/////////////////////////////////////////////////////////////////
//const int colPin = 12;
OneWire oneWire(ONE_WIRE_BUS);// Запуск интерфейса OneWire для подключения OneWire устройств первой линии.
DallasTemperature sensors(&oneWire);// Указание, что устройством oneWire является термодатчик от  Dallas Temperature.
////////////////////////////////////////////////////////////////////
//int address=0;
//void eepromWriteFloat(int address, float volt_element);

//volt_element = eepromReadFloat(address);

void eepromWriteFloat(int address, float floatbyte)
{
   union u_tag
   {
     byte b[4];
     float fval;
   } u;
   u.fval=floatbyte;

   rtc.poke(address  , u.b[0]);
   rtc.poke(address+1, u.b[1]);
   rtc.poke(address+2, u.b[2]);
   rtc.poke(address+3, u.b[3]);
}

float eepromReadFloat(int address)
  {
   union u_tag 
   {
     byte b[4];
     float floatbyte;
   } u;   
   u.b[0] = rtc.peek(address);
   u.b[1] = rtc.peek(address+1);
   u.b[2] = rtc.peek(address+2);
   u.b[3] = rtc.peek(address+3);
   return u.floatbyte;
}
/*byte decToBcd(byte val)
{
  return ( (val/10*16) + (val%10) );
}
 
byte bcdToDec(byte val)
{
  return ( (val/16*10) + (val%16) );
}

void flatint()
{

}
*/
//////////////////////////////////////////////////////
void LcdInitialise(void)
{
  pinMode(PIN_SCE, OUTPUT);
  pinMode(PIN_RESET, OUTPUT);
  pinMode(PIN_DC, OUTPUT);
  pinMode(PIN_SDIN, OUTPUT);
  pinMode(PIN_SCLK, OUTPUT);
  digitalWrite(PIN_RESET, LOW);
  digitalWrite(PIN_RESET, HIGH);
  LcdWrite(LCD_C, 0x21 );  // LCD Extended Commands.
  LcdWrite(LCD_C, 0xBC );  // Set LCD Vop (Contrast). 
  LcdWrite(LCD_C, 0x04 );  // Set Temp coefficent. //0x04
  LcdWrite(LCD_C, 0x14 );  // LCD bias mode 1:48. //0x13
  LcdWrite(LCD_C, 0x0C );  // LCD in normal mode.
  LcdWrite(LCD_C, 0x20 );
  LcdWrite(LCD_C, 0x0C );
}

void LcdClear()
{
  for (int i=0; i<504; i++) LcdWrite(LCD_D, 0x00);
}

void LcdWrite(byte dc, byte data)
{
  digitalWrite(PIN_DC, dc);
  digitalWrite(PIN_SCE, LOW);
  shiftOut(PIN_SDIN, PIN_SCLK, MSBFIRST, data);
  digitalWrite(PIN_SCE, HIGH);
}

void LcdString(char *characters, int x, int y)
{
  LcdWrite(LCD_C, 0x80 | x);  // Column.
  LcdWrite(LCD_C, 0x40 | y);  // Row.
  while (*characters) LcdCharacter(*characters++);
}

void LcdCharacter(char character)
  {
  for (int index = 0; index < 5; index++) LcdWrite(LCD_D, ASCII[character - 0x20][index]);
  LcdWrite(LCD_D, 0x00);
  }

void LcdXY(int x, int y)
{
  LcdWrite(LCD_C, 0x80 | x);  // Column.
  LcdWrite(LCD_C, 0x40 | y);  // Row.
}

  void LcdPlot (int x, int y)
{
  LcdXY(x,5-(y/8)); //set display address for plot
  int bin=128;
  for (int q=0; q<y%8; q++) bin=bin/2; //calculate pixel position in byte
  LcdWrite(LCD_D, bin); //plot pixel
  float slope=float(47-y)/float(83-x);
  
  for (int j=x+2; j<84; j++) 
    {
    float dy=slope*float(j-x);
    int k=y+round(dy);
    LcdXY(j,5-(k/8)); //set display address for plot
    int bin=128;
    for (int q=0; q<k%8; q++) bin=bin/2; //calculate pixel position in byte
    LcdWrite(LCD_D, bin); //plot pixel
    }
}

void perturb(boolean init=false)
{
  static byte pulseWidth = 0;
  static boolean trackDirection = 1; //counts down / pwm increases
  if (init) 
      {
       pulseWidth = 0;//было 255 инвертирование вовода шим
       trackDirection = 1;
      }
  else 
      {
       // if (lastPanelVolts >= 18.5)
       //if ((panelWatts - lastPanelWatts) > 1)
       if (trackDirection  == 1) //if (lastPanelWatts >= panelWatts) 
            {
             if (pulseWidth != 250) {pulseWidth++;} else {trackDirection = 0;}
     // if (pulseWidth != 0) {pulseWidth--;} else {trackDirection = false;}//было (pulseWidth != 255)инвертирование вовода шим
            // if (pulseWidth != 255) {pulseWidth++;} else {trackDirection = true;}//было (pulseWidth != 0)инвертирование вовода шим
             if ((panelWatts - lastPanelWatts) < 1 ) trackDirection = 0;
          //  if (lastPanelVolts <  16 ) trackDirection = 0;
          }
        else
      //if (lastPanelVolts < 18.0)
     //if ((panelWatts - lastPanelWatts) < -1)
            {
              if (pulseWidth != 0) {pulseWidth--;} else {trackDirection = 1;}
    // if (pulseWidth != 250) {pulseWidth++;} else {trackDirection = true;}//было (pulseWidth != 0)инвертирование вовода ши
            // if (pulseWidth != 0) {pulseWidth--;} else {trackDirection = false;}//было (pulseWidth != 255)инвертирование вовода шим
              if ((lastPanelWatts - panelWatts) >  - 1) trackDirection = 1;

          }
      }
  pwmWrite(3, pulseWidth); //write perturbed PWM value to PWM hardware
 //lastPanelWatts = panelWatts;
 // maxpwmwatts2 = maxpwmwatts;
//  if ((panelWatts - lastPanelWatts) < - 5 ) trackDirection = 1;
   //if ((panelWatts - lastPanelWatts) =  1) trackDirection = 2;
   if (lastPanelVolts >  19 ) trackDirection = 1;
  lastPanelWatts = panelWatts;
}

void setup()
//////////////////////////////////////////////////////
{
    {
          {
          //pinMode(colPin, OUTPUT);
          //Serial.begin(9600);// Запуск СОМ порта.
          //Serial.println("Start temperature measurement");
          sensors.begin(); // Запуск 1 линии сенсоров.
          //sensors2.begin(); // Запуск 2 линии сенсоров.
          }
    // Set the clock to run-mode
    rtc.halt(false);
      
    // Setup LCD to 16x2 characters
    //lcd.begin(16, 2);
    
    // The following lines can be commented out to use the values already stored in the DS1307
  //   rtc.setDOW(SUNDAY);        // Set Day-of-Week to SUNDAY
  //   rtc.setTime( has, 55, 0);     // Set the time to 12:00:00 (24hr format)
  //   rtc.setDate(27, 10, 2014);   // Set the date to October 3th, 2010
    
    // Set SQW/Out rate to 1Hz, and enable SQW
   rtc.setSQWRate(SQW_RATE_1);
   rtc.enableSQW(true);
    }
    {
    unsigned counter; //следующие 2 строчки нужны только при первом запуске, 
 //Читаем счетчик из EEPROM:
   EEPROM_read(24, counter);
 if (counter = 0)
   {
     counter = 1;
     EEPROM_write(0, Umax2);
     EEPROM_write(4, Umax1);
     EEPROM_write(8, Umin);
     EEPROM_write(12, Umain);
     EEPROM_write(16, Umin_2);
     EEPROM_write(20, Umax_2);
     EEPROM_write(24, counter);
   }
 else
   {
   EEPROM_read(0, Umax2);
   EEPROM_read(4, Umax1);
   EEPROM_read(8, Umin);
   EEPROM_read(12, Umain);
   EEPROM_read(16, Umin_2);
   EEPROM_read(20, Umax_2);
   EEPROM_read(24, den);
   EEPROM_read(26, mec);
    }
    }
    /////////////////////////////////////////////
/*    sumwats1= rtc.peek(10);
    sumwats2= rtc.peek(11);
    sumwats1 = sumwats1 * 255;
    sumwats = sumwats2 + sumwats1;
    /////////////////////////////////////////////
    sumwatsday1= rtc.peek(12);
    sumwatsday2= rtc.peek(13);
    sumwatsday1 = sumwatsday1 * 255;
    sumwatsday = sumwatsday2 + sumwatsday1;
*/
   floatbyte = eepromReadFloat(0);
   sumwats = floatbyte;
    
   floatbyte = eepromReadFloat(5);
   sumwatsday = floatbyte;
    //////////////////////////////////////////////
    {
    pinMode(A3, OUTPUT);
    digitalWrite(A3, LOW);
    pinMode(5, INPUT);
    pinMode(4, INPUT);
    //digitalWrite(6, HIGH);
    digitalWrite(5, HIGH);
    digitalWrite(4, HIGH);
    digitalWrite(7, HIGH);
    
        
    LcdInitialise();
    LcdClear();
    LcdString("B",31,1);
    LcdString("B",70,1); //напруга авто аккумуляторов
    LcdString("A",31,2);
    LcdString("V",31,3);
    LcdString("Wp",70,3);
    LcdString("A",31,4);
    LcdString("W",70,4);
    LcdString("A",75,0); //display an A for auto
      
    InitTimersSafe(); 
    bool success = SetPinFrequencySafe(3, frequency);
    }
    {
////////////timer///////////////////////
    currentTime = millis();
    loopTime = currentTime; 
    } 
}



void loop()
{
    {
    currentTime = millis();
    if(currentTime >= (loopTime + 10))  //// проверяем каждые 5мс (200 Гц)
        { 
        if (digitalRead(pin_RIGHT) == LOW)  if (sensorValue != 250) {sensorValue++;} 
        if (digitalRead(pin_LEFT) == LOW)  if (sensorValue != 0) {sensorValue--;}  
        if (digitalRead(pin_SELECT) == LOW)
          {
          
page_1:      
          a = 0;
          c = 3;    
          LcdClear();
          myGLCD.InitLCD();
          myGLCD.setFont(SmallFont);
          myGLCD.clrScr();
          myGLCD.print("Wh",70,8);
          myGLCD.print("Wh",70,16);
          myGLCD.print("PAGE1",10,24);
          myGLCD.print("MENU",10,32);
          myGLCD.print("DEFALT",10,40);
           //////////////////////////////////////////
         
          myGLCD.printNumF(den,0,53,24);
          myGLCD.print(".",65,24);
          myGLCD.printNumF(mec,0,70,24);
            ////////////////////////////////////////////
          delay(200);
          while (a < 1)
              {
               if (c > 5){ c = 1;}
               myGLCD.print(">",0,c*8);
               myGLCD.print(rtc.getDateStr(),10,0);
         /////////////////////////////////////////////////////////////////
           //   sumwats1= rtc.peek(0);
           //   sumwats2= rtc.peek(1);     
           //   myGLCD.printNumF(sumwats1,0,10,8);
         myGLCD.print(dtostrf(sumwatsday,10,0,&tmp[3]),10,8);
            //   myGLCD.printNumF(sumwats2,0,10,16);
         myGLCD.print(dtostrf(sumwats,10,3,&tmp[3]),10,16);
         //////////////////////////////////////////////////////////////////
               if (digitalRead(pin_LEFT) == LOW) 
                   { 
                    myGLCD.print(" ",0,c*8);
                    c = c + 1;  
                   }
               myGLCD.print(">",0,c*8);
               if (digitalRead(pin_RIGHT) == LOW) 
                   { 
                   myGLCD.print(" ",0,c*8);
                   c = c - 1;
                   if (c <= 0){ c = 5;}  
                   }
               if (digitalRead(pin_SELECT) == LOW)
                   { 
                    if (c ==1) 
                      { 
                      sumwatsday = 0;
                      t2 = rtc.getTime();
                      den=t2.date;
                      mec=t2.mon;
                      EEPROM_write(24, den);
                      EEPROM_write(26, mec);
                      goto page_1;
                      } 
                    if (c ==2) { sumwats = 0; goto page_1;}
                  //  if (c ==3) {tmen = 0; goto endmenu;}
                    if (c ==5) 
                       { 
                       Umax2 = 14.2; 
                       Umax1 = 13.8; 
                       Umin = 12.8; 
                      // Umain = 13.7; 
                       Umin_2 = 11.0; 
                       Umax_2 = 14.2; 
                      // sumwatsday = 0; 
                      // sumwats = 0; 
                       sensorValue = 0;
                       brightness = 75;
                       maxwatts = 0;
                       c = 4;
                       digitalWrite(A3, LOW);
                       digitalWrite(13, LOW);
                      // goto page_1;
                       //goto endmenu;
                       }
                   a = a + 1;
                   b_type_c = c;
                   }
                t = rtc.getTime();
                men=t.sec;     
                if (men != men2) {tmen = tmen+1; men2 = men;}
                if (tmen == 59) {tmen = 0; goto endmenu;}
               delay(300);
               myGLCD.update();
               }
           if (c ==3) {tmen = 0; goto endmenu;}
            
          
///MENU////////////////////////////////////////////////////////////////////
     if (c ==4)
        {
menu:
        a = 0;
     //   n = 0;    
        myGLCD.InitLCD();
        myGLCD.setFont(SmallFont);
        myGLCD.clrScr();
        myGLCD.print("MENU",10,0);
        myGLCD.print("LCD",10,8);
        myGLCD.print("TIME",10,16);
        myGLCD.print("BATTERY TYPE",10,24);
        myGLCD.print("LOAD",10,32);
        myGLCD.print("EXIT",10,40);
        delay(200);
        while (a < 1)
            {
             if (m > 5){ m = 1;}
             myGLCD.print(">",0,m*8);
             if (digitalRead(pin_LEFT) == LOW) 
                 { 
                  myGLCD.print(" ",0,m*8);
                  m = m + 1;  
                 }
             myGLCD.print(">",0,m*8);
             if (digitalRead(pin_RIGHT) == LOW) 
                 { 
                 myGLCD.print(" ",0,m*8);
                 m = m - 1;
                 if (m <= 0){ m = 5;}  
                 }
            // myGLCD.printNumF(m,1,48,40);
             if (digitalRead(pin_SELECT) == LOW)
                 { 
                 a = a + 1;
                // n = 1;
                 b_type = m;
                 }
             delay(200);
             myGLCD.update();
             }
         if (m ==5) {goto page_1;}
//LIGHT/////////////////////////////////////////////////////////////////// 
         if (m ==1) 
             {
             myGLCD.InitLCD();
             myGLCD.setFont(SmallFont);
             myGLCD.clrScr();
             myGLCD.print("LIGHT",23,0);
             delay(100);
             while (a < 2  )
                 {
                 if (digitalRead(pin_LEFT) == LOW)  if (brightness != 255) {brightness = brightness + 5;} 
                 if (digitalRead(pin_RIGHT) == LOW)  if (brightness != 0) {brightness = brightness - 5;}
                 analogWrite(6, brightness);   // устанавливаем яркость на 6 ножку чтоб в меню тоже управлялась 
                 myGLCD.printNumF(brightness,1,23,20);
                 if (digitalRead(pin_SELECT) == LOW)
                     { 
                     a = a + 1;
                     b_type = m;
                     }
                 delay(200);
                 myGLCD.update();
                 }

            goto  menu;
            }
////TIME//////////////////////////////////////////////////////////////////////////
         if (m ==2)   
            {
menu_3:
             int n = 4;
             LcdClear();
             myGLCD.InitLCD();
             myGLCD.setFont(SmallFont);
             myGLCD.clrScr();
             myGLCD.print("TIME",25,0);
             myGLCD.print("h",10,8);
             myGLCD.print("m",10,16);
             myGLCD.print("DATA",10,24);
             myGLCD.print("EXIT",10,32);
             delay(100);
             while (a < 2  ) 
                 {
                  myGLCD.printNumF(has,0,55,8);
                  myGLCD.printNumF(mi,0,55,16);
                 if (n > 4){ n = 1;}
                  myGLCD.print(">",0,n*8);
                  if (digitalRead(pin_LEFT) == LOW) 
                      { 
                       myGLCD.print(" ",0,n*8);
                       n = n + 1;  
                       }
                  if (n < 5){myGLCD.print(">",0,n*8);} // засвeтка 5 позиц курсора                      
                  if (digitalRead(pin_RIGHT) == LOW) 
                       { 
                       myGLCD.print(" ",0,n*8);
                       n = n - 1;
                       if (n <= 0){ n = 4;}  
                       }
                       myGLCD.print(rtc.getTimeStr(),15,40);
                 //  myGLCD.printNumF(n,1,48,40);
                   if (digitalRead(pin_SELECT) == LOW)
                       { 
                         if (n ==4) {goto menu;}
                         if (n ==3)
menu_4:                       
             {
             int n = 4;
             LcdClear();
             myGLCD.InitLCD();
             myGLCD.setFont(SmallFont);
             myGLCD.clrScr();
             myGLCD.print("PAGE2",25,0);
             myGLCD.print("den",10,8);
             myGLCD.print("mec",10,16);
             myGLCD.print("god",10,24);
             myGLCD.print("PAGE1",10,32);
             delay(100);
             while (a < 2  ) 
                 {
                  myGLCD.printNumF(den,0,55,8);
                  myGLCD.printNumF(mec,0,55,16);
                  myGLCD.printNumF(god,0,55,24);
                 if (n > 4){ n = 1;}
                  myGLCD.print(">",0,n*8);
                  if (digitalRead(pin_LEFT) == LOW) 
                      { 
                       myGLCD.print(" ",0,n*8);
                       n = n + 1;  
                       }
                  if (n < 5){myGLCD.print(">",0,n*8);} // засвeтка 5 позиц курсора                      
                  if (digitalRead(pin_RIGHT) == LOW) 
                       { 
                       myGLCD.print(" ",0,n*8);
                       n = n - 1;
                       if (n <= 0){ n = 4;}  
                       }
                       myGLCD.print(rtc.getDateStr(),15,40);
                   if (digitalRead(pin_SELECT) == LOW)
                       { 
                         if (n ==4) {goto menu_3;}
                            while (a < 2)
                              {
                                if (n ==1) {time=den;}
                                if (n ==2) {time=mec;}
                                if (n ==3) {time=god;}
                                myGLCD.print(" ",0,n*8);
                                myGLCD.print(">",48,n*8);
                                if (n ==1)  {if (digitalRead(pin_RIGHT) == LOW) if  (time != 31) { time = time + 1; }}
                                if (n ==2)  {if (digitalRead(pin_RIGHT) == LOW) if  (time != 12) { time = time + 1; }}
                                if (n ==3)  {if (digitalRead(pin_RIGHT) == LOW) if  (time != 2050) { time = time + 1; }}
                                if (digitalRead(pin_LEFT) == LOW) if (time != 1) { time = time - 1; }
                                if (n ==1) {den=time;}
                                if (n ==2) {mec=time;}
                                if (n ==3) {god=time;}
                                delay(200);
                                myGLCD.printNumF(time,0,55,n*8);
                                myGLCD.update();
                                if (digitalRead(pin_SELECT) == LOW) 
                                    {
                                      
                                      //rtc.setDOW(SUNDAY);        // Set Day-of-Week to SUNDAY
                                     // rtc.setTime( has, mi, 0);     // Set the time to 12:00:00 (24hr format)
                                      rtc.setDate(den, mec, god);   // Set the date to October 3th, 2010
                                      if (n <= 3) {goto menu_4;}
                                       a = a + 1;
                                       b_type_n = n;
                                    }
                               }
                       }        
                 delay(200);
                 myGLCD.update(); 
                 }
                 
              if (n ==4) 
              {
               goto menu_3;
              }
           }
/////////////////////////////////////////////////////////////////////   n не равно 3 
                            while (a < 2)
                              {
                                if (n ==1) {time=has;}
                                if (n ==2) {time=mi;}
                                myGLCD.print(" ",0,n*8);
                                myGLCD.print(">",48,n*8);
                                if (n ==1)  {if (digitalRead(pin_RIGHT) == LOW) if  (time != 23) { time = time + 1; }}
                                if (n ==2)  {if (digitalRead(pin_RIGHT) == LOW) if  (time != 59) { time = time + 1; }}
                                if (digitalRead(pin_LEFT) == LOW) if (time != 0) { time = time - 1; }
                                if (n ==1) {has=time;}
                                if (n ==2) {mi=time;}
                                delay(200);
                                myGLCD.printNumF(time,0,55,n*8);
                                myGLCD.update();
                                if (digitalRead(pin_SELECT) == LOW) 
                                    {
                                      //rtc.setDOW(SUNDAY);        // Set Day-of-Week to SUNDAY
                                      rtc.setTime( has, mi, 0);     // Set the time to 12:00:00 (24hr format)
                                     // rtc.setDate(27, 10, 2014);   // Set the date to October 3th, 2010
                                      if (n <= 2) {goto menu_3;}
                                       a = a + 1;
                                       b_type_n = n;
                                    }
                               }
                       }        
                 delay(200);
                 myGLCD.update(); 
                 }
              if (n ==4) 
              {
                goto menu;
               }
           } 
        
////Charging lead//////////////////////////////////////////////////////////////////////////////////////// 
         if (m ==3)   
            {
menu_1:    
             LcdClear();
             myGLCD.InitLCD();
             myGLCD.setFont(SmallFont);
             myGLCD.clrScr();
             myGLCD.print("Charging lead",3,0);
             myGLCD.print("U max2",10,8);
             myGLCD.print("U max1",10,16);
             myGLCD.print("U min",10,24);
             myGLCD.print("EXIT",10,32);
             delay(100);
             while (a < 2  ) 
                 {
                  myGLCD.printNumF(Umax2,1,55,8);
                  myGLCD.printNumF(Umax1,1,55,16);
                  myGLCD.printNumF(Umin,1,55,24);
                  if (n > 4){ n = 1;}
                  myGLCD.print(">",0,n*8);
                  if (digitalRead(pin_LEFT) == LOW) 
                      { 
                       myGLCD.print(" ",0,n*8);
                       n = n + 1;  
                       }
                  if (n < 5){myGLCD.print(">",0,n*8);} // засвeтка 5 позиц курсора                      
                  if (digitalRead(pin_RIGHT) == LOW) 
                       { 
                       myGLCD.print(" ",0,n*8);
                       n = n - 1;
                       if (n <= 0){ n = 4;}  
                       }
                  // myGLCD.printNumF(n,1,48,40);
                   if (digitalRead(pin_SELECT) == LOW)
                       { 
                         if (n ==4) {goto menu;}
                            while (a < 2)
                              {
                                if (n ==1) {Umenu=Umax2;}
                                if (n ==2) {Umenu=Umax1;}
                                if (n ==3) {Umenu=Umin;}
                                myGLCD.print(" ",0,n*8);
                                myGLCD.print(">",48,n*8);
                                if (digitalRead(pin_RIGHT) == LOW) if (Umenu <= 30.1) { Umenu = Umenu + 0.1; }
                                if (digitalRead(pin_LEFT) == LOW) if (Umenu >= 5.50) { Umenu = Umenu - 0.1; }
                                if (n ==1) {Umax2=Umenu;}
                                if (n ==2) {Umax1=Umenu;}
                                if (n ==3) {Umin=Umenu;}
                                delay(200);
                                myGLCD.printNumF(Umenu,1,55,n*8);
                                myGLCD.update();
                                if (digitalRead(pin_SELECT) == LOW) 
                                    {
                                      if (n <= 3) {goto menu_1;}
                                       a = a + 1;
                                       b_type_n = n;
                                    }
                               }
                       }        
                 delay(200);
                 myGLCD.update(); 
                 }
            if (n ==4) {goto menu;}
            }
//Load//////////////////////////////////////////////////////////////////////////////////////////
         if (m ==4)   
            {
menu_2:              
             LcdClear();
             myGLCD.InitLCD();
             myGLCD.setFont(SmallFont);
             myGLCD.clrScr();
             myGLCD.print("Load",25,0);
             myGLCD.print("U onn",10,8);
             myGLCD.print("U off",10,16);
             myGLCD.print("EXIT",10,24);
             myGLCD.print("U main",10,32);
             delay(100);
             while (a < 2  ) 
                 {
                  myGLCD.printNumF(Umax_2,1,55,8);
                  myGLCD.printNumF(Umin_2,1,55,16);
                  if (n > 3){ n = 1;}
                  myGLCD.print(">",0,n*8);
                  if (digitalRead(pin_LEFT) == LOW) 
                      { 
                       myGLCD.print(" ",0,n*8);
                       n = n + 1;  
                       }
                  if (n < 4){myGLCD.print(">",0,n*8);} // засвeтка 4 позиц курсора                      
                  if (digitalRead(pin_RIGHT) == LOW) 
                       { 
                       myGLCD.print(" ",0,n*8);
                       n = n - 1;
                       if (n <= 0){ n = 3;}  
                       }
                  // myGLCD.printNumF(n,1,48,40);
                   myGLCD.printNumF(batteryVolts,1,55,32);
                   if (digitalRead(pin_SELECT) == LOW)
                       { 
                         if (n ==3) {goto menu;}
                            while (a < 2)
                              {
                                if (n ==1) {Umenu=Umax_2;}
                                if (n ==2) {Umenu=Umin_2;}
                                myGLCD.print(" ",0,n*8);
                                myGLCD.print(">",48,n*8);
                                if (digitalRead(pin_RIGHT) == LOW) if (Umenu <= 30.1) { Umenu = Umenu + 0.1; }
                                if (digitalRead(pin_LEFT) == LOW) if (Umenu >= 5.50) { Umenu = Umenu - 0.1; }
                                if (n ==1) {Umax_2=Umenu;}
                                if (n ==2) {Umin_2=Umenu;}
                                delay(200);
                                myGLCD.printNumF(Umenu,1,55,n*8);
                                myGLCD.update();
                                if (digitalRead(pin_SELECT) == LOW) 
                                    {
                                      if (n <= 2) {goto menu_2;}
                                       a = a + 1;
                                       b_type_n = n;
                                    }
                               }
                       }        
                 delay(200);
                 myGLCD.update(); 
                 }
            if (n ==4) {goto menu;}
            }
        }
////////////////////////////////////////////////////////////////////////////////////////////
endmenu:
        EEPROM_write(0, Umax2);
        EEPROM_write(4, Umax1);
        EEPROM_write(8, Umin);
        EEPROM_write(12, Umain);
        EEPROM_write(16, Umin_2);
        EEPROM_write(20, Umax_2);
        LcdClear();
        myGLCD.InitLCD();
        myGLCD.setFont(SmallFont);
        myGLCD.clrScr();
        LcdString("B",31,1);
        LcdString("B",70,1); //напруга авто аккумуляторов
        LcdString("A",31,2);
        LcdString("V",31,3);
        LcdString("Wp",70,3);
        LcdString("A",31,4);
        LcdString("W",70,4);
        LcdString("A",75,0); //display an A for auto
        }
    //panelAmps = sensorValue; ////test
    analogWrite(6, brightness);   // устанавливаем яркость на 6 ножку 
    loopTime = currentTime;
    }
    }
// Получаем значение времени 
t = rtc.getTime();
 //getDateDs1307(byte sek,byte mi,byte has);
sek=t.sec;
mi=t.min;
has=t.hour;
 if (sek == 1) {if (mi == 0) {if (has == 0) {sumwats=0; maxwatts=0;}}} 
 if (sek != sek2)
     {
       sek2=sek;
       sumwats = sumwats + (lastPanelWatts / 3600);
       /////////////////////////////////////////
      // floatbyte = eepromReadFloat(0);
       //sumwats = floatbyte;
       floatbyte = sumwats;
       eepromWriteFloat(0, floatbyte);
       
       //adress = 0;
       
       ////////////////////////////////////////////
/*       sumwats1 =sumwats / 255;
       rtc.poke(10, sumwats1);
       rtc.poke(11, sumwats);
*/
       sumwatsday = sumwatsday + (lastPanelWatts / 3600);
       floatbyte = sumwatsday;
       eepromWriteFloat(5, floatbyte);
/*       sumwatsday1 =sumwats / 255;
       rtc.poke(12, sumwatsday1);
       rtc.poke(13, sumwatsday);
*/
     }
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
panelVolts = (analogRead(A1) * 0.0293) * 2; //get the volts
panelVolts = (panelVolts + lastPanelVolts) / 2; //average the volts
lastPanelVolts = panelVolts;
LcdString(dtostrf(panelVolts,5,2,&tmp[0]),0,3); //display the volts

 panelAmps = (analogRead(A2)-512) * 0.0782; //get the panelAmps
// panelAmps = analogRead(A2);
panelAmps = (panelAmps + lastPanelAmps) / 2; //average the panelAmps
lastPanelAmps = panelAmps;
if (panelAmps < 0.02) panelAmps = 0.01; //don't let the panelAmps go below zero
LcdString(dtostrf(panelAmps,5,2,&tmp[1]),0,4); //display the panelAmps
  
panelWatts = panelVolts * panelAmps; //calculate the watts
LcdString(dtostrf(panelWatts,4,1,&tmp[2]),40,4); //display the panel watts
///////////////////////////////////////////////////////////////////
  
  if (lastBatteryVolts > Umax1) {digitalWrite(A3, HIGH);}
 // Umain=lastBatteryVolts-0.2;
  if (lastBatteryVolts < batteryVolts_2) {digitalWrite(A3, LOW);}
  if (lastBatteryVolts >= Umax_2) {digitalWrite(13, HIGH);}
  if (lastBatteryVolts <= Umin_2) {digitalWrite(13, LOW);}

/////////////////////////////////////////////////////////////////////////////////////////////
// ограничение напряжения
  if (batteryVolts >= Umax2)
    {
    LcdString("OK",70,5); // можно не ставить вывод на экран
    mpptOn = false; 
    }
  else
  //if (batteryVolts <= Umin)
    {
    LcdString("  ",70,5);// можно не ставить вывод на укран
   // mpptOn = true;
    }
  LcdString(rtc.getTimeStr(),15,0);
  /////////////////////////////////////////////////////////
  if ((panelWatts - lastPanelWatts) < -0.1) maxpwmwatts=1;
  if ((panelWatts - lastPanelWatts) > 0.1) maxpwmwatts=0;
 //maxpwmwatts = panelWatts - lastPanelWatts;

  
//sensorValue = analogRead(A3);

if (sensorValue < 5)// было (sensorValue < 1022)
  {
  if (mpptOn) 
    {
    perturb();
    }
else 
    {
    mpptOn = true;
    perturb(initialise); //initialise the perturb algorithm
    LcdString("A",75,0); //display an A for auto
    }
  }
else 
  {
    LcdString("M",75,0); //display an M for manual
  if (!mpptOn)
    {
    pwmWrite(3, sensorValue); //255
    }
  else 
    {
    mpptOn = false;
    }
  }
  
//  lastPanelWatts = panelWatts;
//lastmaxpwmwatts = maxpwmwatts;

  
batteryVolts = analogRead(A6) * 0.0293; //get the battery volts
batteryVolts = (batteryVolts + lastBatteryVolts) / 2; //average the volts
lastBatteryVolts = batteryVolts;
LcdString(dtostrf(batteryVolts,5,2,&tmp[0]),0,1); //display the battery volts

batteryVolts_2 = analogRead(A0) * 0.0293; //get the battery volts
batteryVolts_2 = (batteryVolts_2 + lastBatteryVolts_2) / 2; //average the volts
lastBatteryVolts_2 = batteryVolts_2;
LcdString(dtostrf(batteryVolts_2,5,2,&tmp[4]),40,1); //display the battery volts
  
batteryAmps = (analogRead(A7)-513)*0.0783; //get the panelAmps
//batteryAmps = analogRead(A5);
batteryAmps = (batteryAmps + lastBatteryAmps) / 2; //average the panelAmps
lastBatteryAmps = batteryAmps;
if (batteryAmps < 0.02) batteryAmps = 0.01; //don't let the batteryAmps go below zero
LcdString(dtostrf(batteryAmps,5,2,&tmp[1]),0,2); //display the batteryAmps
  
  
maxwatts = max(maxwatts, panelWatts); //calculate the max watts

LcdString(dtostrf(maxwatts,4,1,&tmp[3]),40,3); //display the max watts
  
  
if (panelWatts > 27) highWatts = true; //go to 83Watt bargraph
  
  
LcdXY(0,5);
if (!highWatts) 
  {
  barwatts = round(panelWatts * 3);
  for(int k=0; k<84; k++)
    {
    if (k >= barwatts) LcdWrite (LCD_D, 0x00);
    else if (k % 30 == 0) LcdWrite (LCD_D, 0xf0);
    else if (k % 15 == 0) LcdWrite (LCD_D, 0xe0);
    else LcdWrite (LCD_D, 0xc0);
    }
  }
else 
  {
  barwatts = round(panelWatts);
  for(int k=0; k<84; k++)
    {
    if (k >= barwatts) LcdWrite (LCD_D, 0x00);
    else if (k % 10 == 0) LcdWrite (LCD_D, 0xf0);
    else if (k % 5 == 0) LcdWrite (LCD_D, 0xe0);
    else LcdWrite (LCD_D, 0xc0);
    }
  }
  
  
Voc = max(Voc, panelVolts); 
Isc = max(Isc, panelAmps);
if (chartX > 41 & chartY > 23) //if in upper right quadrant
  { 
  LcdPlot (chartX, chartY);
  }
////////////////////////////////////////////////////////////////
  {
    { 
    //  digitalWrite(colPin, LOW);
    if (T3 >= 150)// Таймер опроса шины температуры
      {
      // опрос:    
      sensors.requestTemperatures(); // Команда опроса температуры первой шины.
      // Serial.println("Please wait...");
      //Serial.print("T1=");
      //Serial.println(sensors.getTempCByIndex(0)); // Печать в порт температуры, "0" в данном случае указывает на первое устройство в шине. 
      float T1=sensors.getTempCByIndex(0);
      LcdString("T1=",45,2); //  вывод1 на экран
      LcdString(dtostrf(T1,4,2,&tmp[1]),60,2);        
      T3 = 0;
      }
    else
      {
      T3 = (T3 + 1);
      }
    }
  }
  



/////////////////////////////////////////////////////////////  
  delay(100);
}


