// 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-му пину Ардуино.
/////////////////////////////////////////////////////////////

int a1 =11;

//#include <stdlib.h>;
#include <avrasm.h>
#include "header.h";
#include <PWM.h>
#include <DS1307.h>
/////////////////////////////////////////////////////////////
#include <OneWire.h>// Инициализация библиотеки шины OneWire.
#include <DallasTemperature.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);

int sensorValue = 0;
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 batteryWatts = 0;
float maxwatts = 0;
float Umenu = 0;
int barwatts = 0;
float Voc = 0;
float Isc = 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 a = 0; 
int b = 0;
int c = 3;
int m = 1; 
int n = 1;
int b_type;
int b_type_n;
int b_type_c;
float Umax2 = 14.2;
float Umax1 = 13.8;
float Umin = 12.8;
float Umain = 13.7;
float Umin_2 = 11.0;
float Umax_2 = 13.7;
float sumwatsday = 0;
float sumwats = 0;
int has = 0;
int mi = 0;
int den = 1;
int mec = 1;
int god = 2010;
//////////////////////////////////////////////////////////////////
int brightness = 120;       // яркость LED, начинаем с половины
int fadeAmount = 10;        // шаг изменения яркости 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.
////////////////////////////////////////////////////////////////////

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 = false; //counts down / pwm increases
  if (init) 
      {
       pulseWidth = 0;//было 255 инвертирование вовода шим
       trackDirection = false;
      }
  else 
      {
        if (!trackDirection) 
            {
             if (pulseWidth != 255) {pulseWidth++;} else {trackDirection = true;}//было (pulseWidth != 0)инвертирование вовода шим
            }
        else
            {
             if (pulseWidth != 0) {pulseWidth--;} else {trackDirection = false;}//было (pulseWidth != 255)инвертирование вовода шим
            }
      }
  pwmWrite(3, pulseWidth); //write perturbed PWM value to PWM hardware
  if ((panelWatts - lastPanelWatts) < -0.1) trackDirection = !trackDirection;
  
}

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);
    }
//////////////////////////////////////////////////////
    {
    pinMode(A3, OUTPUT);
    digitalWrite(A3, LOW);
    pinMode(5, INPUT);
    pinMode(4, INPUT);
    //digitalWrite(6, HIGH);
    digitalWrite(5, HIGH);
    digitalWrite(4, HIGH);
        
    LcdInitialise();
    LcdClear();
    LcdString("B",31,1);
    LcdString("B",70,1); //напруга авто аккумуляторов
    LcdString("A",31,2);
    LcdString("V",31,3);
    LcdString("Wp",65,3);
    LcdString("A",31,4);
    LcdString("W",65,4);
    LcdString("A",75,4); //display an A for auto
      
    InitTimersSafe(); 
    bool success = SetPinFrequencySafe(3, frequency);
    }
    {
////////////timer///////////////////////
    currentTime = millis();
    loopTime = currentTime; 
    } 
}



void loop()
{
    {
    currentTime = millis();
    if(currentTime >= (loopTime + 5))  //// проверяем каждые 5мс (200 Гц)
        { 
        if (digitalRead(pin_LEFT) == LOW)  if (sensorValue != 250) {sensorValue++;} 
        if (digitalRead(pin_RIGHT) == 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("W",75,8);
          myGLCD.print("W",75,16);
          myGLCD.print("PAGE1",10,24);
          myGLCD.print("MENU",10,32);
          myGLCD.print("DEFALT",10,40);
          delay(200);
          while (a < 1)
              {
               if (c > 5){ c = 1;}
               myGLCD.print(">",0,c*8);
               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;}  
                   }
                   myGLCD.printNumF(sumwatsday,0,10,8);
                   myGLCD.printNumF(sumwats,0,10,16);
                   myGLCD.print(rtc.getDateStr(),10,0);
               if (digitalRead(pin_SELECT) == LOW)
                   { 
                    if (c ==1) { sumwatsday = 0; goto page_1;} 
                    if (c ==2) { sumwats = 0; goto page_1;}
                    if (c ==5) 
                       { 
                       Umax2 = 14.2; 
                       Umax1 = 13.8; 
                       Umin = 12.8; 
                      // Umain = 13.7; 
                       Umin_2 = 11.0; 
                       Umax_2 = 13.7; 
                       sumwatsday = 0; 
                       sumwats = 0; 
                       sensorValue = 0;
                       brightness = 120;
                       maxwatts = 0;
                       c = 4;
                      // goto page_1;
                       //goto endmenu;
                       }
                   a = a + 1;
                   b_type_c = c;
                   }
               delay(200);
               myGLCD.update();
               }
           if (c ==3) {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) {Umenu=den;}
                                if (n ==2) {Umenu=mec;}
                                if (n ==3) {Umenu=god;}
                                myGLCD.print(" ",0,n*8);
                                myGLCD.print(">",48,n*8);
                                if (n ==1)  {if (digitalRead(pin_LEFT) == LOW) if  (Umenu != 31) { Umenu = Umenu + 1; }}
                                if (n ==2)  {if (digitalRead(pin_LEFT) == LOW) if  (Umenu != 12) { Umenu = Umenu + 1; }}
                                if (n ==3)  {if (digitalRead(pin_LEFT) == LOW) if  (Umenu != 2050) { Umenu = Umenu + 1; }}
                                if (digitalRead(pin_RIGHT) == LOW) if (Umenu != 1) { Umenu = Umenu - 1; }
                                if (n ==1) {den=Umenu;}
                                if (n ==2) {mec=Umenu;}
                                if (n ==3) {god=Umenu;}
                                delay(200);
                                myGLCD.printNumF(Umenu,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) {Umenu=has;}
                                if (n ==2) {Umenu=mi;}
                                myGLCD.print(" ",0,n*8);
                                myGLCD.print(">",48,n*8);
                                if (n ==1)  {if (digitalRead(pin_LEFT) == LOW) if  (Umenu != 24) { Umenu = Umenu + 1; }}
                                if (n ==2)  {if (digitalRead(pin_LEFT) == LOW) if  (Umenu != 60) { Umenu = Umenu + 1; }}
                                if (digitalRead(pin_RIGHT) == LOW) if (Umenu != 0) { Umenu = Umenu - 1; }
                                if (n ==1) {has=Umenu;}
                                if (n ==2) {mi=Umenu;}
                                delay(200);
                                myGLCD.printNumF(Umenu,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_LEFT) == LOW) if (Umenu <= 30.1) { Umenu = Umenu + 0.1; }
                                if (digitalRead(pin_RIGHT) == 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_LEFT) == LOW) if (Umenu <= 30.1) { Umenu = Umenu + 0.1; }
                                if (digitalRead(pin_RIGHT) == 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:
        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",65,3);
        LcdString("A",31,4);
        LcdString("W",65,4);
        LcdString("A",75,4); //display an A for auto
        }
    //panelAmps = sensorValue; ////test
    analogWrite(6, brightness);   // устанавливаем яркость на 6 ножку 
    loopTime = currentTime;
    }
    }
    
 sumwatsday = maxwatts; 
 sumwats = panelWatts; 
  
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)-509) * 0.0782; //get the panelAmps
// panelAmps = analogRead(A2);
panelAmps = (panelAmps + lastPanelAmps) / 2; //average the panelAmps
lastPanelAmps = panelAmps;
if (panelAmps < 0.02) panelAmps = 0; //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(13, HIGH);}
 // Umain=lastBatteryVolts-0.2;
  if (lastBatteryVolts <= lastBatteryVolts_2) {digitalWrite(13, LOW);}
  if (lastBatteryVolts >= Umax_2) {digitalWrite(A3, HIGH);}
  if (lastBatteryVolts <= Umin_2) {digitalWrite(A3, LOW);}

/////////////////////////////////////////////////////////////////////////////////////////////
// ограничение напряжения
  if (batteryVolts >= Umax2)
    {
    LcdString("OK",70,5); // можно не ставить вывод на экран
    mpptOn = false; 
    }
  else
  //if (batteryVolts <= Umin)
    {
    LcdString("  ",70,5);// можно не ставить вывод на укран
   // mpptOn = true;
    }
  LcdString(rtc.getTimeStr(),15,0);
//sensorValue = analogRead(A3);
if (sensorValue < 5)// было (sensorValue < 1022)
  {
  if (mpptOn) 
    {
    perturb();
    }
else 
    {
    mpptOn = true;
    perturb(initialise); //initialise the perturb algorithm
    LcdString("A",75,4); //display an A for auto
    }
  }
else 
  {
    LcdString("M",75,4); //display an M for manual
  if (!mpptOn)
    {
    pwmWrite(3, sensorValue); //255
    }
  else 
    {
    mpptOn = false;
    }
  }
  
lastPanelWatts = panelWatts;
  
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)-510)*0.0783; //get the panelAmps
//batteryAmps = analogRead(A5);
batteryAmps = (batteryAmps + lastBatteryAmps) / 2; //average the panelAmps
lastBatteryAmps = batteryAmps;
if (batteryAmps < 0.02) batteryAmps = 0; //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(10);
}



