 #include <LiquidCrystal_I2C.h>
#include <Wire.h>
#include <EEPROM.h>
#include <math.h>

int var;
int func_sleep = 6;//для режима сна 
int val_DCIn;
int menu = 7;// кнопка menu
int plus = 8;//кнопка +
int minus = 9;// кнопка -
int offtl = 10; //1-тушим TL,0-работает ТЛ-ка 
int rele = 12;//реле на питание
int out_PWM = 11;// выход управления PWM
int zadaniy_tok;
int hotstart;
int Forsage;
int sleep;
int hot_start;
int antizalip;
int termo2;
int termo1;
float valpwm;
float max_valpwm=200;//наш максимальный ток
float hotstart_pwm;
float forsage_pwm;
int DCIn_status = 0;
unsigned long Timer_zapis_toka;
unsigned long Timer_DCIn;
unsigned long Timer_antizalip;
LiquidCrystal_I2C lcd(0x27, 20, 4);  // инициализация библиотеки дисплея
unsigned long time; //таймер в милисекундах
unsigned long time_sec;// таймер в секундах
int val_sleep = 0;//dlya funkcii sleep
/////  Обработка температуры с терморезисторов  ////
double Thermister(int RawADC) {
	double Temp;
	Temp = log(((10240000/RawADC) - 10000));
	Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp ))* Temp );
	Temp = Temp - 273.15;		// Kelvin to Celcius
	return Temp;
}
  
///////////////////////////////////////////////////
void setup ()
{
analogReference(DEFAULT); 
digitalWrite(offtl, HIGH);
zadaniy_tok = EEPROM.read(0);
hotstart = EEPROM.read(1);
Forsage = EEPROM.read(2);
sleep = EEPROM.read(3);
antizalip = EEPROM.read(4);
lcd.init();          // Старт дисплея
Wire.begin();        // старт I2C
lcd.backlight();     // Включаем подсветку дисплея
pinMode(8, INPUT);
pinMode(9, INPUT);
pinMode(10, OUTPUT);  
pinMode(11, OUTPUT);
pinMode(12, OUTPUT); 
tok_setup();
byte znak_termo[8] = {0b01100,0b10010,0b10010,0b01100,0b00000,0b00000,0b00000,0b00000};// 
lcd.createChar(0, znak_termo);
byte odin[8] = {0b11111,0b11101,0b11001,0b10101,0b11101,0b11101,0b11101,0b11111};//
lcd.createChar(1, odin);
byte dva[8] = {0b11111,0b10001,0b11101,0b11101,0b10001,0b10111,0b10001,0b11111};//
lcd.createChar(2, dva);
lcd.setCursor(0, 0);
lcd.print("Welcom to forum:");
lcd.setCursor(0, 1);
lcd.print("    CXEM.NET    ");
delay(2000);
lcd.clear();
lcd.print("   Thank you!   ");
lcd.setCursor(0, 1);
lcd.print(" Oleg1ma & KT117");
delay(2000);
lcd.clear();
digitalWrite(rele, HIGH);//включаем реле
digitalWrite(offtl, LOW);// разрешаем ТЛ-ке генерить
//На случай если в EPROM будет какойто бред, например при первой прошивке - когда ище не выставлены значения етих функций 
if(zadaniy_tok>=201){zadaniy_tok=20;}
if(hotstart>=101){hotstart=0;}
if(Forsage>=101){Forsage=0;}
if(antizalip>=2){antizalip=0;}
//////////////////////////////////
}

void loop()
{

termo1=(Thermister(analogRead(0))); //читаем температуру с 1 терморезистора 
termo2=(Thermister(analogRead(2))); //читаем температуру с 2 терморезистора 
time_sec=time/1000;
time = millis();
noTone(3);
obnovlenie_ekrana();
if(termo1 >= 70 || termo2 >= 70){tone(3, 2000);delay(100);noTone(3);delay(100);tone(3, 2000);delay(100);noTone(3);lcd.clear();avariya ();}
analogWrite(out_PWM, valpwm);
val_sleep = analogRead(func_sleep); //4itaem 6 pin funkcii slip
val_DCIn = analogRead(A7); 
if (sleep>0){lcd.setCursor(15, 0);lcd.print("S");}
if (antizalip>0){lcd.setCursor(13, 0);lcd.print("A");}
if (Forsage>0){lcd.setCursor(14, 0);lcd.print("F");}
if (hotstart>0){lcd.setCursor(12, 0);lcd.print("H");}
    lcd.setCursor(0, 0);
    lcd.print("TOK= ");
    lcd.print(zadaniy_tok);
    lcd.print("A");
    lcd.setCursor(0, 1);
    lcd.write((byte) 1);
    lcd.print(termo1);
    lcd.write((byte) 0);
    lcd.setCursor(11, 1);
    lcd.write((byte) 2);
    lcd.print(termo2);
    lcd.write((byte) 0);
if (digitalRead(menu)==1){tone(3, 2000);lcd.clear();delay(500);menu_menu ();}/// Vhod v MENU

/////////////////// Таймер записи выставленного Тока ////////////////////// 
                   if ((time - Timer_zapis_toka)>=60000 && EEPROM.read(0) != zadaniy_tok)
                    {  
                      lcd.clear();
                      lcd.setCursor(0, 0);
                      lcd.print("===== Save =====");
                      lcd.setCursor(0, 1);
                                 int var;
                                  var = 0;
                                 while(var < 16)
                                 {
                                  lcd.print("\xff");
                                  var++;
                                  delay(50);
                                  }                                    
                             lcd.clear();
                             EEPROM.write(0, zadaniy_tok);
                    } 
////////////////////////////////////////////////////////////////////////////

if(val_DCIn >= 150){hot_start=0;}
// DCIn_status = 1;// не варим
// DCIn_status = 0;//варим
///==== HOT Start =====================
if (hot_start==0 && DCIn_status==1 && val_DCIn <= 400 && hotstart !=0)
{
 if(valpwm+valpwm*hotstart/100 >= max_valpwm){hotstart_pwm=max_valpwm;}else hotstart_pwm=valpwm+valpwm*hotstart/100;
       hot_start=1;
       analogWrite(out_PWM, hotstart_pwm); 
       lcd.clear();
       lcd.setCursor(0, 1);
       lcd.print("    HOT START    ");
       delay(500);
       DCIn_status=0;
       lcd.clear();
}
///////////////////////////////////////
//========== СОН ==========
if(val_DCIn >= 400 && DCIn_status == 0 )
      {
       Timer_DCIn = time_sec; 
       DCIn_status = 1;//govorim 4to mi nerabotaem
      } 
if(val_DCIn <= 400 && DCIn_status ==1){DCIn_status = 0;Timer_antizalip=time_sec;}//Varim
if(DCIn_status == 1 && sleep != 0 && (time_sec - Timer_DCIn) >= sleep)
          {
              tone(3, 2000);
              delay(100);
              noTone(3);
              delay(100);
              tone(3, 2000);
              delay(100);
              noTone(3);
              lcd.clear();
              son ();
          }
///////////////////////////////////
//.......... AntiStick.......//////////////  
if(val_DCIn <= 70 && antizalip ==1 && (time_sec - Timer_antizalip)>=2)
    {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("!! Anti Stick !!");
      digitalWrite(offtl, HIGH);
      tone(3, 2000);
      lcd.noBacklight();
      delay(500);
      noTone(3);
      lcd.backlight();
      delay(500);
      tone(3, 2000);
      lcd.noBacklight();
      delay(500);
      noTone(3);
      lcd.backlight();
      delay(500);
      tone(3, 2000);
      lcd.noBacklight();
      delay(500);
      noTone(3);
      lcd.backlight();
      delay(500);
      tone(3, 2000);
      lcd.noBacklight();
      delay(500);
      lcd.backlight();
      delay(500);
      noTone(3);
      digitalWrite(offtl, LOW);
      Timer_antizalip=time_sec;
      lcd.clear();
}
//////////////////////////////////////////////////
///==== Forsage =====================
if (DCIn_status==0 && val_DCIn <= 100 && Forsage !=0)
  {
   if(valpwm+valpwm*Forsage/100 >= max_valpwm){forsage_pwm=max_valpwm;}else forsage_pwm=valpwm+valpwm*Forsage/100;
   
       lcd.clear();
       lcd.setCursor(0, 1);
       lcd.print("    FORSAGE    ");
       analogWrite(out_PWM, forsage_pwm);
       delay(500);
       DCIn_status=0;
       lcd.clear();
}
///////////////////////////////////////
}

void obnovlenie_ekrana()
{
  
if (digitalRead(plus)==1&&zadaniy_tok!=200)
       { 
        time_sec=time/1000;
       time = millis();    
       zadaniy_tok=zadaniy_tok+5;
       tok_setup();
       tone(3, 2000);
       delay(200);
       Timer_zapis_toka=time;
       Timer_DCIn = time_sec;
       noTone(3);
       } 
if (digitalRead(minus)==1&&zadaniy_tok!=20)
      { 
      time_sec=time/1000;
      time = millis();    
      zadaniy_tok=zadaniy_tok-5;
      tok_setup();
      tone(3, 2000);
      delay(200);
      Timer_zapis_toka=time;
      Timer_DCIn = time_sec;
      noTone(3);
      }
}



void tok_setup()
    {
      valpwm=zadaniy_tok;
      if(zadaniy_tok==95){lcd.clear();}
    }
    
void avariya ()
{
termo1=(Thermister(analogRead(0)));  
termo2=(Thermister(analogRead(2)));
noTone(3);
while(termo1 >= 45 || termo2 >= 45)
{
 termo1=(Thermister(analogRead(0)));  
 termo2=(Thermister(analogRead(2)));
  digitalWrite(offtl, HIGH);
  lcd.setCursor(0, 0);
  lcd.print(" = PEREGREV = ");
  lcd.setCursor(0, 1);
  lcd.write((byte) 1);
  lcd.print(termo1);
  lcd.setCursor(11, 1);
  lcd.write((byte) 2);
  lcd.print(termo2);
  delay(1000);
} 
 tone(3, 2000);
 delay(100);
 noTone(3);
 delay(100);
 tone(3, 2000);
 delay(100);
 noTone(3);
 lcd.clear();
 digitalWrite(offtl, LOW);
 loop(); 
}

void son ()
{
  noTone(3);
val_sleep = analogRead(6); //4itaem 6 pin funkcii slip
while(val_sleep > 400)
{
  time_sec=time/1000;
  time = millis();
  val_sleep = analogRead(6); //4itaem 6 pin funkcii slip
  digitalWrite(offtl, HIGH);
  lcd.setCursor(0, 0);
  lcd.print("  === COH ===  ");
  
} 
tone(3, 2000);
 delay(100);
 noTone(3);
 delay(100);
 tone(3, 2000);
 delay(100);
 noTone(3);
 DCIn_status = 0;
 Timer_DCIn = time_sec;
 lcd.clear();
 digitalWrite(offtl, LOW);
 loop(); 

}



//==================== MENU ===========================
void menu_menu ()
{
   if (var==0)  {
                
                lcd.setCursor(0, 0);
                lcd.print("===== MENU =====");
                lcd.setCursor(0, 1);
                lcd.print("     Select    >");
                //if (digitalRead(menu)==1){tone(3, 2000);lcd.clear();delay(1000);return;}
                
                }
  if (var==1)  {
                
                lcd.setCursor(0, 0);
                lcd.print("===== MENU =====");
                lcd.setCursor(0, 1);
                lcd.print("<   Hot Start  >");
                if (digitalRead(menu)==1){tone(3, 2000);lcd.clear();delay(200);menu_hot_start ();}

                }
 if (var==2)  {
                
                lcd.setCursor(0, 0);
                lcd.print("===== MENU =====");
                lcd.setCursor(0, 1);
                lcd.print("<   Forsage    >");
                if (digitalRead(menu)==1){tone(3, 2000);lcd.clear();delay(200);menu_Forsage ();}
                }                
 if (var==3)  {
                
                lcd.setCursor(0, 0);
                lcd.print("===== MENU =====");
                lcd.setCursor(0, 1);
                lcd.print("<    Sleep     >");
                if (digitalRead(menu)==1){tone(3, 2000);lcd.clear();delay(200);menu_sleep ();}
                }                

 if (var==4)  {
                
                lcd.setCursor(0, 0);
                lcd.print("===== MENU =====");
                lcd.setCursor(0, 1);
                lcd.print("<  Anti Stick  >");
                if (digitalRead(menu)==1){tone(3, 2000);lcd.clear();delay(200);menu_zalip ();}
                }               
 if (var==5)  {
                
                lcd.setCursor(0, 0);
                lcd.print("===== MENU =====");
                lcd.setCursor(0, 1);
                lcd.print("<     EXIT     ");
                if (digitalRead(menu)==1){tone(3, 2000);lcd.clear();delay(1000);var=0;Timer_DCIn = time_sec;return;}
                }                               

       if (digitalRead(plus)==1&&var!=5)
       {     
       var=var+1;
      tone(3, 2000);
       delay(200);
       lcd.clear();
        } 
        if (digitalRead(minus)==1&&var!=0)
       {     
       var=var-1;
      tone(3, 2000);
       delay(200);
       lcd.clear();
        } 
noTone(3);
menu_menu ();
}
  
 
 
 void menu_hot_start ()
{
  noTone(3);

                lcd.setCursor(0, 0);
                lcd.print("===== MENU =====");
                lcd.setCursor(0, 1);
                lcd.print("Hot Start = ");
                lcd.print(hotstart);
               lcd.print("%");
if (digitalRead (plus)==1&&hotstart!=100)
       {
    
         if (hotstart >=100){hotstart=10;}
      hotstart=hotstart+1;
      tone(3, 2000);
       delay(100);
        } 
if (digitalRead(minus)==1&&hotstart!=0)
      {     
      hotstart=hotstart-1;
      tone(3, 2000);
      if(hotstart==9){lcd.clear();}
      if(hotstart==99){lcd.clear();}
      delay(100);
      }
if (digitalRead(menu)==1){
                          if (EEPROM.read(1) != hotstart) {
                          EEPROM.write(1, hotstart);
                          }
    tone(3, 2000);lcd.clear();delay(2000);var=1;exit;} 
  else menu_hot_start ();                
      
} 



void menu_Forsage ()
{
  noTone(3);

                lcd.setCursor(0, 0);
                lcd.print("===== MENU =====");
                lcd.setCursor(0, 1);
                lcd.print(" Forsage = ");
                lcd.print(Forsage);
                lcd.print("%");
               
if (digitalRead (plus)==1&&Forsage!=100)
       {
       
       Forsage=Forsage+1;
      tone(3, 2000);
       delay(100);
      
        } 
if (digitalRead(minus)==1&&Forsage!=0)
      { 
          
      Forsage=Forsage-1;
      tone(3, 2000);
      delay(100);
      lcd.clear();
      }
if (digitalRead(menu)==1){
                          if (EEPROM.read(2) != Forsage) {
                          EEPROM.write(2, Forsage);
                          }
    tone(3, 2000);lcd.clear();delay(2000);var=2;exit;} 
  else menu_Forsage ();                
       
}



void menu_sleep ()
{
    noTone(3);

                lcd.setCursor(0, 0);
                lcd.print("===== MENU =====");
                lcd.setCursor(0, 1);
                lcd.print(" Sleep = ");
                lcd.print(sleep);
                lcd.print("cek.");
               
if (digitalRead (plus)==1&&sleep!=300)
       {
       
       sleep=sleep+1;
      tone(3, 2000);
       delay(100);
      
        } 
if (digitalRead(minus)==1&&sleep!=0)
      { 
          
      sleep=sleep-1;
      tone(3, 2000);
      delay(100);
      lcd.clear();
      }
if (digitalRead(menu)==1){
                          if (EEPROM.read(3) != sleep) {
                          EEPROM.write(3, sleep);
                          }
    tone(3, 2000);lcd.clear();delay(2000);var=3;exit;} 
  else menu_sleep ();     
}

void menu_zalip ()
{
      noTone(3);

                lcd.setCursor(0, 0);
                lcd.print("===== MENU =====");
                lcd.setCursor(0, 1);
                lcd.print(" Anti Stick ");
                //lcd.print(antizalip);
                if (antizalip==1){lcd.print("On");}
                if (antizalip==0){lcd.print("Off");}
               
if (digitalRead (plus)==1&&antizalip!=1)
       {
       
       antizalip=antizalip+1;
      tone(3, 2000);
       delay(200);
      lcd.clear();
        } 
if (digitalRead(minus)==1&&antizalip!=0)
      { 
          
      antizalip=antizalip-1;
      tone(3, 2000);
      delay(200);
      lcd.clear();
      }
if (digitalRead(menu)==1){
                          if (EEPROM.read(4) != antizalip) {
                          EEPROM.write(4, antizalip);
                          }
    tone(3, 2000);lcd.clear();delay(2000);var=4;exit;} 
  else menu_zalip ();     
  
}

//===============END MENU =========================



