пауза без delay

sergey555
Offline
Зарегистрирован: 21.09.2016

Доброго времени всем!

У меня  постала задача поставить на электрокотел контроллер для управления нагревом. В котле присуцтвует 9 тен, соответственно 9 реле которые включают тенны.

Управляются реле через здвиговые регистыры.

Вроди как все получилось, но не могу справится с одной задачей:

нужно  чтобы реле последовательно включались с интервало, допустим 5 секунд.

delay не подходит, так как зависает считывание показаний с датчиков и управление кнопками.

Millis тоже не подходит (ну возможно подходит, только я не понимаю) потому, что в процесе работы программы, изменяя какие то параметры (например включение\выключение, или выбор режима "ЕКО") реле включаются хаотично, не учитывая заданых интервалов в Millis.

Подскажите кто может, пожалуйста!! Как решить такову пробллему?

Зарание спасибо огромное!!!

ЕвгенийП
ЕвгенийП аватар
Offline
Зарегистрирован: 25.05.2015

sergey555 пишет:

Millis тоже не подходит (ну возможно подходит, только я не понимаю) потому, что в процесе работы программы, изменяя какие то параметры (например включение\выключение, или выбор режима "ЕКО") реле включаются хаотично, не учитывая заданых интервалов в Millis.

Реле не могут включаться хаотично (если у Вас по схеме помехи не гуляют как по бульвару). Они включаются точно тогда, когда их включает Ваша программа.

Давайте код и схему, посмотрим что там вызывает хаос.

sergey555
Offline
Зарегистрирован: 21.09.2016

Здравствуйте ЕвгенийП!

Спасибо большое что откликнулись! Схемы как таковой нет, потому, что потключаюсь Ардуиной к старой плате управления, на которой вылетел контроллер. Принцип очень простой - на здвиговые регистры отправляются 2 байта информации. Схемы не рисовал.)

Не судите очень громко)) так как только учусь и всего 2 недели как впервые попробовал програмировать!Чувствую что в коде много безсмысленных строк... Но пока смог только так!

// Термометр будет подключен на Pin 0
#include <EEPROM2.h> // Подключаем библиотеку для работы с ARDUINO EEPROM
#include <LiquidCrystal.h>
#include <OneWire.h> // Подключаем библиотеку для работы с шиной OneWire
#include <DallasTemperature.h>//Подключаем библиотеку для работы с термометром66
#include <Shift595.h>              // подключим библиотеку для работы со здвиговыми регистрами

// обьявим модуль для работы с здвиговыми регистрами
#define   dataPin           3      // pin 14 on the 74HC595
#define   latchPin          1      // pin 12 on the 74HC595
#define   clockPin          2      // pin 11 on the 74HC595
#define   numOfRegisters    2      // количество регистров сдвига 
Shift595 Shifter(dataPin, latchPin, clockPin, numOfRegisters);

LiquidCrystal lcd(8, 9, 4, 5, 6, 7); //Подключаем LCD-дисплей

// создаем переменные для определения давления в системе отопления
float analogSens = A1; //Подключаем датчик давления к аналоговому выводу А1
float bar;    //создаем переменную давления в барылях
float val = analogRead(analogSens);;
float bar1;// переменная для хранения состояния давления
boolean on_off = 0;//переменная для хранения состояния включения котла
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
OneWire oneWire(0);
DallasTemperature sensors(&oneWire);//Создаем объект sensors, подключенный по OneWire

//Создаем переменные для работы с термометром
DeviceAddress tempDeviceAddress;  //переменная для хранения адреса датчика

//Define Variables we'll be connecting to
//double Setpoint, Input, Output;

float temp1 = 0; //переменная для текущего значения температуры
int setTmp = 0; // переменная для заданного значения температуры
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

int eco = 0; //....................................................................................................
int eco33 = 33;
int eco66 = 66;

//Подсветка управляется через пин D10
#define BACKLIGHT_PIN 10
//Создаем переменную для хранения состояния подсветки
boolean backlightStatus = 1;


//Объявим переменные для задания задержки измерения температуры
long previousMillis1 = 0;
long interval1 = 1000; // интервал опроса датчиков температуры

// Объявим переменные для задания задержки включения реле нагревателей
long previousMillis2 = 0;  //----------------------------------------------------------------------------------
long interval2 = 3000;
long previousMillis3 = 0;
long interval3 = 6000;
long previousMillis4 = 0;
long interval4 = 9000;
long previousMillis5 = 0;
long interval5 = 12000;
long previousMillis6 = 0;
long interval6 = 15000;
long previousMillis7 = 0;
long interval7 = 18000;
long previousMillis8 = 0;
long interval8 = 21000;
long previousMillis9 = 0;
long interval9 = 24000;

#define KEYPAD_PIN A0
//Определим значения на аналоговом входе для клавиатуры
#define ButtonUp_LOW 129
#define ButtonUp_HIGH 133
#define ButtonDown_LOW 306
#define ButtonDown_HIGH 311
#define ButtonLeft_LOW 479
#define ButtonLeft_HIGH 483
#define ButtonRight_LOW 0
#define ButtonRight_HIGH 50
#define ButtonSelect_LOW 717
#define ButtonSelect_HIGH 725

void setup()
{

  Shifter.clearRegisters();

  //Считаем из постоянной памяти заданную температуру
  setTmp = EEPROM_read_byte(0); //Заданная температура будет храниться по адресу 0
  sensors.getAddress(tempDeviceAddress, 0);
  
 //Считаем из постоянной памяти выбраный режим...................................................................
  eco = EEPROM_read_byte(1); //выбраный режим будет храниться по адресу 1

//Считаем из постоянной памяти состояние включения котла...................................................................
   on_off = EEPROM_read_byte(2); //выбраный режим будет храниться по адресу 2
  
  //Настроим подсветку дисплея
  pinMode(BACKLIGHT_PIN, OUTPUT);
  digitalWrite(BACKLIGHT_PIN, backlightStatus);

  //Выведем на дисплей стартовое сообщение на 2 секунды
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("ANGELINKA LOVE");
  lcd.setCursor(0, 1);
  lcd.print("      v1.0      ");
  delay(1000);

  // выведем на дисплей заданное значение температуры на 2 секунды
  lcd.setCursor(0, 1);
  lcd.print("  Set temp:     ");
  lcd.setCursor(12, 1);
  lcd.print(setTmp);
  delay(100);

  //Очистим дисплей
  lcd.clear();//lcd.begin(16, 2);
}

//Определим функцию для опроса аналоговой клавиатуры
//Функция опроса клавиатуры, принимает адрес пина, к которому подключена клавиатура, и возвращает код клавиши:
// 1 - UP
// 2 - DOWN
// 3 - LEFT
// 4 - RIGHT
// 5 - SELECT

int ReadKey(int keyPin)
{
  int KeyNum = 0;
  int KeyValue1 = 0;
  int KeyValue2 = 0;

  //Читаем в цикле аналоговый вход, для подавления дребезга и нестабильности
  //читаем по два раза подряд, пока значения не будут равны.
  //Если значения равны 1023 – значит не была нажата ни  одна клавиша.

  do {
    KeyValue1 = analogRead(keyPin);
    KeyValue2 = analogRead(keyPin);
  } while (KeyValue1 == KeyValue2 && KeyValue2 != 1023);

  //Интерпретируем полученное значение и определяем код нажатой клавиши
  if (KeyValue2 < ButtonUp_HIGH && KeyValue2 > ButtonUp_LOW) {
    KeyNum = 1; //Up
  }
  if (KeyValue2 < ButtonDown_HIGH && KeyValue2 > ButtonDown_LOW) {
    KeyNum = 2; //Down
  }
  if (KeyValue2 < ButtonLeft_HIGH && KeyValue2 > ButtonLeft_LOW) {
    KeyNum = 3; //Left
  }
  if (KeyValue2 < ButtonRight_HIGH && KeyValue2 > ButtonRight_LOW) {
    KeyNum = 4; //Right
  }
  if (KeyValue2 < ButtonSelect_HIGH && KeyValue2 > ButtonSelect_LOW) {
    KeyNum = 5; //Select
  }
  //Возвращаем код нажатой клавиши
  return KeyNum;
}

//Определим процедуру редактирования заданной температуры
//Вызывается по нажатию клавиши Select, отображает на дисплее заданную
//температуру и позволяет изменять ее клавишами Up и Down

void setTemperature() {

  int keyCode = 0;

  //выводим на дисплей заданное значение температуры
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("YCTAHOBKA TEMP");
  lcd.setCursor(7, 1);
  lcd.print(setTmp);


  //Опрашиваем клавиатуру, если нажата клавиша Up увеличиваем значение на 1, если Down – уменьшаем на 1
  //Если нажаты клавиши Select или Right – цикл опроса прерывается
  //Задержки введены для борьбы с дребезгом, если клавиши срабатывают четко – можно уменьшить время задержек или вообще их убрать
  do {
    keyCode = ReadKey(KEYPAD_PIN);
    if (keyCode == 1)
    {
      setTmp++;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(setTmp);
    }
    if (keyCode == 2)
    {
      setTmp--;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(setTmp);
    }
  } while (keyCode != 5 && keyCode != 4);
  lcd.clear();
  delay(200);

  //По клавише Select – сохраняем в EEPROM измененное значение
  //По клавише Right – восстанавливаем старое значение
  if (keyCode == 5) {
    EEPROM_write_byte(0, setTmp);
  }
  if (keyCode == 4) {
    setTmp = EEPROM_read_byte(0);
  }
}
void ecoRegim() {
  int keyCode1 = 0;
  //выводим на дисплей выбраный режим
  lcd.begin(16, 2);
  lcd.setCursor(3, 0);
  lcd.print("REGIM ECO");
  lcd.setCursor(7, 1);
  lcd.print(eco);
  lcd.setCursor(9, 1);
  lcd.print('%');

  do {
    keyCode1 = ReadKey(KEYPAD_PIN);
    if (keyCode1 == 1)//включаем еко режим на 33%
    {
      eco = eco33;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(eco);
      lcd.setCursor(9, 1);
      lcd.print('%');
    }
    if (keyCode1 == 2)//включаем еко режим на 66%
    {
      eco = eco66;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(eco);
      lcd.setCursor(9, 1);
      lcd.print('%');
    }
    if (keyCode1 == 4)//отключаем еко режим
    {
      eco = 0;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print("OFF");
    }
  } while (keyCode1 != 3);
  lcd.clear();
  delay(200);

  //По клавише Left – сохраняем в EEPROM измененное значение
  if (keyCode1 == 3) {
    EEPROM_write_byte(1, eco);
  }
}
void boilerStart(){
  int keyCode2 = 0;
//lcd.clear();//lcd.begin(16, 2);
  //выводим на дисплей заданное значение температуры
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("COCTOYANIE KOTLA");
  lcd.setCursor(7, 1);
  lcd.print(on_off);


  //Опрашиваем клавиатуру, если нажата клавиша Up увеличиваем значение на 1, если Down – уменьшаем на 1
  //Если нажаты клавиши Select или Right – цикл опроса прерывается
  //Задержки введены для борьбы с дребезгом, если клавиши срабатывают четко – можно уменьшить время задержек или вообще их убрать
  do {
    keyCode2 = ReadKey(KEYPAD_PIN);
    if (keyCode2 == 4&&on_off==0)
    {
      on_off=1;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(on_off);
     // while(on_off==1);
    }
    if (keyCode2 == 3&&on_off==1)
    {
      on_off=0;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(on_off);
    //while(on_off==0);
    }
  } while (keyCode2 != 5);
  lcd.clear();
  delay(200);

  //По клавише Select – сохраняем в EEPROM измененное значение
  //По клавише Right – восстанавливаем старое значение
  if (keyCode2 == 5) {
    EEPROM_write_byte(2, on_off);
  }
}
void loop() {

  //Модуль опроса датчика температуры и получения сведений о температуре
  //Вызывается 1 раз в секунду
  unsigned long currentMillis1 = millis();
  if (currentMillis1 - previousMillis1 > interval1)
  {
    previousMillis1 = currentMillis1;
    //Запуск процедуры измерения температуры
    sensors.setWaitForConversion(false);
    sensors.requestTemperatures();
    sensors.setWaitForConversion(true);

    // delay(50); // задержка для обработки информации внутри термометра, в данном случае можно не задавать

    //Считывание значения температуры
    sensors.getAddress(tempDeviceAddress, 0);
    temp1 = sensors.getTempC(tempDeviceAddress);
    // Вывод текущего значения температуры на дисплей
    lcd.setCursor(0, 0);
    lcd.print("TEMP");
    lcd.setCursor(5, 0);
    lcd.print(temp1);
    lcd.setCursor(0, 1);
    lcd.print("sTEMP");
    lcd.setCursor(6, 1);
    lcd.print(setTmp);

  }
  // создаем модуль считывания значения с датчика давления в системе и конвертации в барыль
  {
    //int sensorBar = analogRead(analogPin1); //создаем переменную для чтения показаний датчика и читаем показания
    // float bar = sensorBar*5./1024.*2.; //преобразуем показания датчика в барыли
    //delay(100);

    val = analogRead(analogSens);
    val = constrain (val, 60,  700);
    bar = map(val, 60, 700, 0, 45);
    bar1 = bar / 10;
    lcd.setCursor(9, 1);
    lcd.print("BAR");
    lcd.setCursor(13, 1);
    lcd.print(bar1);
  }


  /////////////////////////////////////////////////////////////////////////////////////////////////////////////
  //Проверка условия включения/выключения нагревателя
 
  ////////////////////////////////////////////////////////////////////////////////////////////////////////////
  if (eco == 33&&on_off==1) {
    if (temp1 < setTmp && temp1 > setTmp - 0.5 && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=11%E");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, LOW);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, LOW);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, LOW);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else if (temp1 < setTmp && temp1 > setTmp - 1 && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=22%E");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, LOW);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, LOW);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else if (temp1 < setTmp && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=33%E");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, LOW);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, HIGH);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }

    }
    else
    { lcd.setCursor(9, 0);
      lcd.print(" P=0%E ");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, LOW);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, LOW);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, LOW);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, LOW);
      }
    }
  }
  
  ////////////////////////////////////////////////////////////////////////////////////////////////////////////
  else if (eco == 66&&on_off==1) {
    if (temp1 < setTmp && temp1 > setTmp - 0.5 && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=11%E");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, LOW);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, LOW);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, LOW);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else if (temp1 < setTmp && temp1 > setTmp - 1 && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=22%E");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, LOW);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, LOW);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else if (temp1 < setTmp && temp1 > setTmp - 1.5 && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=33%E");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, LOW);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, HIGH);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }

    }
    else if (temp1 < setTmp && temp1 > setTmp - 2 && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=44%E");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, HIGH);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, HIGH);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else if (temp1 < setTmp && temp1 > setTmp - 2.5 && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=55%E");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, HIGH);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, HIGH);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, HIGH);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else if (temp1 < setTmp && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=66%E");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, HIGH);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, HIGH);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, HIGH);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, HIGH);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else
    { lcd.setCursor(9, 0);
      lcd.print(" P=0%E ");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, LOW);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, LOW);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, LOW);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, LOW);
      }
    }
  }
  
  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  else if(eco==0&&on_off==1)  {
    if (temp1 < setTmp && temp1 > setTmp - 0.5 && bar1 > -1 && bar1 < 3&&on_off==1)
    { lcd.setCursor(9, 0);
      lcd.print(" P=11% ");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, LOW);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, LOW);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, LOW);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else if (temp1 < setTmp && temp1 > setTmp - 1 && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=22% ");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, LOW);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, LOW);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else if (temp1 < setTmp && temp1 > setTmp - 1.5 && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=33% ");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, LOW);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, HIGH);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }

    }
    else if (temp1 < setTmp && temp1 > setTmp - 2 && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=44% ");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, HIGH);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, HIGH);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else if (temp1 < setTmp && temp1 > setTmp - 2.5 && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=55% ");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, HIGH);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, HIGH);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, HIGH);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else if (temp1 < setTmp && temp1 > setTmp - 3 && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=66% ");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, HIGH);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, HIGH);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, HIGH);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, HIGH);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else if (temp1 < setTmp && temp1 > setTmp - 3.5 && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=77% ");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, HIGH);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, HIGH);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, HIGH);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, HIGH);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, HIGH);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else if (temp1 < setTmp && temp1 > setTmp - 4 && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=88% ");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, HIGH);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, HIGH);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, HIGH);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, HIGH);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, HIGH);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, HIGH);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else if ( temp1 < setTmp && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=100%");
      Shifter.setRegisterPin(5, HIGH);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, HIGH);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, HIGH);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, HIGH);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, HIGH);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, HIGH);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, HIGH);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else
    { lcd.setCursor(9, 0);
      lcd.print(" P=0%  ");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, LOW);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, LOW);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, LOW);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, LOW);
      }
    }
  }
    else if (on_off==0)
    { lcd.setCursor(9, 0);
      lcd.print(" P=0  ");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, LOW);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, LOW);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, LOW);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, LOW);
      }
    }
  
 
  ///////////////////////////////////////////////////////////////////////////////////////////////////////

  // Опрос клавиатуры
  int Feature = ReadKey(KEYPAD_PIN);

  //Включение подсветки
  if (Feature == 1 )
  {
    backlightStatus = 1;
    digitalWrite(BACKLIGHT_PIN, backlightStatus);
  }

  //Отключение подсветки
  if (Feature == 2 )
  {
    backlightStatus = 0;
    digitalWrite(BACKLIGHT_PIN, backlightStatus);
  }

  //Переход к редактированию заданной температуры
  if (Feature == 5 )
  { delay(200); setTemperature();
  }
  //Переход к редактированию еко режима
  if (Feature == 3 )
  { delay(200); ecoRegim();
  }
   //Переход к включению\выключению котла
  if (Feature == 4 )
  { delay(200); boilerStart();
  }
}

 

Dimanoss
Offline
Зарегистрирован: 29.05.2016

вот это полотно!  :-)  sergey555, однотипные (идентичные) переменные, к которым применяются одни и те же операции, лучше паковать в массивы, а обработку их проводить циклично, функциями - так и код в разы сократиться (будет и места меньше в памяти занимать и читабельнее станет), и проект в целом легко масштабировать можно будет.

ЕвгенийП
ЕвгенийП аватар
Offline
Зарегистрирован: 25.05.2015

Понятно, Сергей.

Поправьте меня, если я где-то навру:

1. Вы хотите иметь интервал между включениями / выключениями, чтобы они не включались все сразу и не давали резкую нагрузку. Сейчас у Вас установлен интервал в три секунды.

2. Включение и выключение котлов производится с блоках (номера строк): 352-395, 397-440, 442-484, ... 1309-1351.

3. Все эти блоки одинаковые, за исключением строки для вывода на экран (типа "lcd.print(" P=0  ");") и параметров HIGH/LOW в вызовах функции Shifter.setRegisterPin. Кстати, и чего бы их не оформить функцией с двумя параметрами? Программа бы в разы сократилось, ну, да ладно.

4. Хаотичность выражается в том, что пока там они включаются, может поступить новая команда - включаться по-другому. При этом все переменные, хранящие текущие millis уже имеют значения, в общем голову сломаешь, пока их починишь и всё настроишь.

Пожалуйста, поправьте, если что не так.

Теперь вопрос к Вам. Устроит ли Вас чтобы каждый тэн имел своё фиксированное время включения/выключения? Например, на нулевой секунде может вкл/выкл только первый (другие - никогда), на третьей - воторой, на шестой - третий, ... на 24-ой - девятый, и снова - на 27-ой - первый, на 30-ой - второй и т.д.

Т.е. допустим первый двигатель может вкл/выкл только на 0-ой, 27-ой, 54-ой и т.д. секундах. В промежутках он всегда остаётся в том состоянии (включён или выключен), в которое перешёл в последний раз.

Если так устроит, то программу можно поменять очень просто - малой кровью. Расписывать сейчас не буду, т.к. если Вас это не устроит, то чего пиисать? Кстати, если не устроит, то напишите как устроит.

Возможно, я смогу Вам ответить только поздно вечером. Сейчас я в дороге и батарея садится :( Если не успеем пока сядет, то тогда вечером. Пока ответьте мне как сможете.

sergey555
Offline
Зарегистрирован: 21.09.2016

Евгений, Вы все правильно разобрали мою проблему! Спасибо!

Наверно Вы на 100% правы по поводу функций, только я пока не знаю как это делается:)

Я думаю что меня устроит такой вариант, что Вы предлагаете, главное, чтобы при переключении какого то режима работы отщет начинался заново (также как работает delay, только без заморозки выполняемой программы). Конечно, если у меня с Вашей помощью или как там получится, все  начнет работать коректно, то я займусь "порядком"  в самом коде, попробую собрать в функции или в масивы:)! 

sergey555
Offline
Зарегистрирован: 21.09.2016

Dimanoss спасибо большое за совет!

Буду стараться в конечном итоге весь код собрать грамотно!

Просто "я еще не волшебник, я только учусь":)

Пишите подсказки, делитесь знаниями! Не только я а и многие другие будут весьма благодарны за Вышу информацию!! 

ЕвгенийП
ЕвгенийП аватар
Offline
Зарегистрирован: 25.05.2015

Ну, если правильно понял, то давайте попробуем.

// Термометр будет подключен на Pin 0
#include <EEPROM2.h> // Подключаем библиотеку для работы с ARDUINO EEPROM
#include <LiquidCrystal.h>
#include <OneWire.h> // Подключаем библиотеку для работы с шиной OneWire
#include <DallasTemperature.h>//Подключаем библиотеку для работы с термометром66
#include <Shift595.h>              // подключим библиотеку для работы со здвиговыми регистрами


// обьявим модуль для работы с здвиговыми регистрами
#define   dataPin           3      // pin 14 on the 74HC595
#define   latchPin          1      // pin 12 on the 74HC595
#define   clockPin          2      // pin 11 on the 74HC595
#define   numOfRegisters    2      // количество регистров сдвига 
Shift595 Shifter(dataPin, latchPin, clockPin, numOfRegisters);

LiquidCrystal lcd(8, 9, 4, 5, 6, 7); //Подключаем LCD-дисплей

// создаем переменные для определения давления в системе отопления
float analogSens = A1; //Подключаем датчик давления к аналоговому выводу А1
float bar;    //создаем переменную давления в барылях
float val = analogRead(analogSens);;
float bar1;// переменная для хранения состояния давления
boolean on_off = 0;//переменная для хранения состояния включения котла
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
OneWire oneWire(0);
DallasTemperature sensors(&oneWire);//Создаем объект sensors, подключенный по OneWire

//Создаем переменные для работы с термометром
DeviceAddress tempDeviceAddress;  //переменная для хранения адреса датчика

//Define Variables we'll be connecting to
//double Setpoint, Input, Output;

float temp1 = 0; //переменная для текущего значения температуры
int setTmp = 0; // переменная для заданного значения температуры
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

int eco = 0; //....................................................................................................
int eco33 = 33;
int eco66 = 66;

//Подсветка управляется через пин D10
#define BACKLIGHT_PIN 10
//Создаем переменную для хранения состояния подсветки
boolean backlightStatus = 1;


//Объявим переменные для задания задержки измерения температуры
long previousMillis1 = 0;
long interval1 = 1000; // интервал опроса датчиков температуры

// Объявим переменные для задания задержки включения реле нагревателей
long previousMillis2 = 0;  //----------------------------------------------------------------------------------
long interval2 = 3000;
long previousMillis3 = 0;
long interval3 = 6000;
long previousMillis4 = 0;
long interval4 = 9000;
long previousMillis5 = 0;
long interval5 = 12000;
long previousMillis6 = 0;
long interval6 = 15000;
long previousMillis7 = 0;
long interval7 = 18000;
long previousMillis8 = 0;
long interval8 = 21000;
long previousMillis9 = 0;
long interval9 = 24000;

#define KEYPAD_PIN A0
//Определим значения на аналоговом входе для клавиатуры
#define ButtonUp_LOW 129
#define ButtonUp_HIGH 133
#define ButtonDown_LOW 306
#define ButtonDown_HIGH 311
#define ButtonLeft_LOW 479
#define ButtonLeft_HIGH 483
#define ButtonRight_LOW 0
#define ButtonRight_HIGH 50
#define ButtonSelect_LOW 717
#define ButtonSelect_HIGH 725

void setup()
{
  Shifter.clearRegisters();

  //Считаем из постоянной памяти заданную температуру
  setTmp = EEPROM.read(0); //Заданная температура будет храниться по адресу 0
  sensors.getAddress(tempDeviceAddress, 0);
  
 //Считаем из постоянной памяти выбраный режим...................................................................
  eco = EEPROM.read(1); //выбраный режим будет храниться по адресу 1

//Считаем из постоянной памяти состояние включения котла...................................................................
   on_off = EEPROM.read(2); //выбраный режим будет храниться по адресу 2
  
  //Настроим подсветку дисплея
  pinMode(BACKLIGHT_PIN, OUTPUT);
  digitalWrite(BACKLIGHT_PIN, backlightStatus);

  //Выведем на дисплей стартовое сообщение на 2 секунды
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("ANGELINKA LOVE");
  lcd.setCursor(0, 1);
  lcd.print("      v1.0      ");
  delay(1000);

  // выведем на дисплей заданное значение температуры на 2 секунды
  lcd.setCursor(0, 1);
  lcd.print("  Set temp:     ");
  lcd.setCursor(12, 1);
  lcd.print(setTmp);
  delay(100);

  //Очистим дисплей
  lcd.clear();//lcd.begin(16, 2);
}

//Определим функцию для опроса аналоговой клавиатуры
//Функция опроса клавиатуры, принимает адрес пина, к которому подключена клавиатура, и возвращает код клавиши:
// 1 - UP
// 2 - DOWN
// 3 - LEFT
// 4 - RIGHT
// 5 - SELECT

int ReadKey(int keyPin)
{
  int KeyNum = 0;
  int KeyValue1 = 0;
  int KeyValue2 = 0;

  //Читаем в цикле аналоговый вход, для подавления дребезга и нестабильности
  //читаем по два раза подряд, пока значения не будут равны.
  //Если значения равны 1023 – значит не была нажата ни  одна клавиша.

  do {
    KeyValue1 = analogRead(keyPin);
    KeyValue2 = analogRead(keyPin);
  } while (KeyValue1 == KeyValue2 && KeyValue2 != 1023);

  //Интерпретируем полученное значение и определяем код нажатой клавиши
  if (KeyValue2 < ButtonUp_HIGH && KeyValue2 > ButtonUp_LOW) {
    KeyNum = 1; //Up
  }
  if (KeyValue2 < ButtonDown_HIGH && KeyValue2 > ButtonDown_LOW) {
    KeyNum = 2; //Down
  }
  if (KeyValue2 < ButtonLeft_HIGH && KeyValue2 > ButtonLeft_LOW) {
    KeyNum = 3; //Left
  }
  if (KeyValue2 < ButtonRight_HIGH && KeyValue2 > ButtonRight_LOW) {
    KeyNum = 4; //Right
  }
  if (KeyValue2 < ButtonSelect_HIGH && KeyValue2 > ButtonSelect_LOW) {
    KeyNum = 5; //Select
  }
  //Возвращаем код нажатой клавиши
  return KeyNum;
}

//Определим процедуру редактирования заданной температуры
//Вызывается по нажатию клавиши Select, отображает на дисплее заданную
//температуру и позволяет изменять ее клавишами Up и Down

void setTemperature() {

  int keyCode = 0;

  //выводим на дисплей заданное значение температуры
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("YCTAHOBKA TEMP");
  lcd.setCursor(7, 1);
  lcd.print(setTmp);


  //Опрашиваем клавиатуру, если нажата клавиша Up увеличиваем значение на 1, если Down – уменьшаем на 1
  //Если нажаты клавиши Select или Right – цикл опроса прерывается
  //Задержки введены для борьбы с дребезгом, если клавиши срабатывают четко – можно уменьшить время задержек или вообще их убрать
  do {
    keyCode = ReadKey(KEYPAD_PIN);
    if (keyCode == 1)
    {
      setTmp++;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(setTmp);
    }
    if (keyCode == 2)
    {
      setTmp--;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(setTmp);
    }
  } while (keyCode != 5 && keyCode != 4);
  lcd.clear();
  delay(200);

  //По клавише Select – сохраняем в EEPROM измененное значение
  //По клавише Right – восстанавливаем старое значение
  if (keyCode == 5) {
    EEPROM.write(0, setTmp);
  }
  if (keyCode == 4) {
    setTmp = EEPROM.read(0);
  }
}
void ecoRegim() {
  int keyCode1 = 0;
  //выводим на дисплей выбраный режим
  lcd.begin(16, 2);
  lcd.setCursor(3, 0);
  lcd.print("REGIM ECO");
  lcd.setCursor(7, 1);
  lcd.print(eco);
  lcd.setCursor(9, 1);
  lcd.print('%');

  do {
    keyCode1 = ReadKey(KEYPAD_PIN);
    if (keyCode1 == 1)//включаем еко режим на 33%
    {
      eco = eco33;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(eco);
      lcd.setCursor(9, 1);
      lcd.print('%');
    }
    if (keyCode1 == 2)//включаем еко режим на 66%
    {
      eco = eco66;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(eco);
      lcd.setCursor(9, 1);
      lcd.print('%');
    }
    if (keyCode1 == 4)//отключаем еко режим
    {
      eco = 0;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print("OFF");
    }
  } while (keyCode1 != 3);
  lcd.clear();
  delay(200);

  //По клавише Left – сохраняем в EEPROM измененное значение
  if (keyCode1 == 3) {
    EEPROM.write(1, eco);
  }
}
void boilerStart(){
  int keyCode2 = 0;
//lcd.clear();//lcd.begin(16, 2);
  //выводим на дисплей заданное значение температуры
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("COCTOYANIE KOTLA");
  lcd.setCursor(7, 1);
  lcd.print(on_off);


  //Опрашиваем клавиатуру, если нажата клавиша Up увеличиваем значение на 1, если Down – уменьшаем на 1
  //Если нажаты клавиши Select или Right – цикл опроса прерывается
  //Задержки введены для борьбы с дребезгом, если клавиши срабатывают четко – можно уменьшить время задержек или вообще их убрать
  do {
    keyCode2 = ReadKey(KEYPAD_PIN);
    if (keyCode2 == 4&&on_off==0)
    {
      on_off=1;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(on_off);
     // while(on_off==1);
    }
    if (keyCode2 == 3&&on_off==1)
    {
      on_off=0;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(on_off);
    //while(on_off==0);
    }
  } while (keyCode2 != 5);
  lcd.clear();
  delay(200);

  //По клавише Select – сохраняем в EEPROM измененное значение
  //По клавише Right – восстанавливаем старое значение
  if (keyCode2 == 5) {
    EEPROM.write(2, on_off);
  }
}


static uint16_t	allTenStates = 0;
#define	TEN(x)	((uint16_t)1 << (x))	// Маска тена. 1 в нулевом бите - нулевой тэн, в 1-ом - 1-ый и т.д.
#define	TEN_OPERATION_INTERVAL	3000UL	// Реальные операции с тенами не чаще (в мс) и только по одному тэну
#define	TOTAL_TENS	9UL	// Всего тэнов
#define	TEN_PINS	{ 5, 2, 9, 4, 1, 7, 3, 13, 10 } // номера пинов для тэнов (тэны подряд с 0-го по 8-ой)

static void setupHeaters(const char * title, const uint16_t toLow, const uint16_t toHigh) {
	lcd.setCursor(9, 0);
	lcd.print(title);
	allTenStates |= toHigh;
	allTenStates &= ~toHigh;
}

static void realSetupHeaters(const unsigned long currMillis) {
	static unsigned long intervalCounter = -1;
	const unsigned long threeSecsInterval = currMillis / TEN_OPERATION_INTERVAL;
	if (threeSecsInterval == intervalCounter) return;
	intervalCounter = threeSecsInterval;
	const uint8_t currentTen = (intervalCounter % TOTAL_TENS);
	static const int8_t tenPins[] = TEN_PINS;
	Shifter.setRegisterPin(tenPins[currentTen], (allTenStates & TEN(currentTen)) ? HIGH : LOW);
}

void loop() {
  //Модуль опроса датчика температуры и получения сведений о температуре
  //Вызывается 1 раз в секунду
  unsigned long currentMillis1 = millis();

	// Выполнить реальные операции с тэнами, если пришло время.
	realSetupHeaters(currentMillis1);

  if (currentMillis1 - previousMillis1 > interval1)
  {
    previousMillis1 = currentMillis1;
    //Запуск процедуры измерения температуры
    sensors.setWaitForConversion(false);
    sensors.requestTemperatures();
    sensors.setWaitForConversion(true);

    // delay(50); // задержка для обработки информации внутри термометра, в данном случае можно не задавать

    //Считывание значения температуры
    sensors.getAddress(tempDeviceAddress, 0);
    temp1 = sensors.getTempC(tempDeviceAddress);
    // Вывод текущего значения температуры на дисплей
    lcd.setCursor(0, 0);
    lcd.print("TEMP");
    lcd.setCursor(5, 0);
    lcd.print(temp1);
    lcd.setCursor(0, 1);
    lcd.print("sTEMP");
    lcd.setCursor(6, 1);
    lcd.print(setTmp);

  }
  // создаем модуль считывания значения с датчика давления в системе и конвертации в барыль
  {
    //int sensorBar = analogRead(analogPin1); //создаем переменную для чтения показаний датчика и читаем показания
    // float bar = sensorBar*5./1024.*2.; //преобразуем показания датчика в барыли
    //delay(100);

    val = analogRead(analogSens);
    val = constrain (val, 60,  700);
    bar = map(val, 60, 700, 0, 45);
    bar1 = bar / 10;
    lcd.setCursor(9, 1);
    lcd.print("BAR");
    lcd.setCursor(13, 1);
    lcd.print(bar1);
  }


  /////////////////////////////////////////////////////////////////////////////////////////////////////////////
  //Проверка условия включения/выключения нагревателя
 
  ////////////////////////////////////////////////////////////////////////////////////////////////////////////
  if (eco == 33&&on_off==1) {
    if (temp1 < setTmp && temp1 > setTmp - 0.5 && bar1 > -1 && bar1 < 3)
    {
		// ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
		setupHeaters(
			" P=11%E", 	/* что выводить на экран */
			TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7), /* в какие тены записать LOW */
			TEN(8) /* в какие тены записать HIGH */
		);
//    	lcd.setCursor(9, 0);
//      lcd.print(" P=11%E");
//      Shifter.setRegisterPin(5, LOW);
//      unsigned long currentMillis2 = millis();
//      if (currentMillis2 - previousMillis2 > interval2)
//      { previousMillis2 = currentMillis2;
//        Shifter.setRegisterPin(2, LOW);
//      }
//      unsigned long currentMillis3 = millis();
//      if (currentMillis3 - previousMillis3 > interval3)
//      { previousMillis3 = currentMillis3;
//        Shifter.setRegisterPin(9, LOW);
//      }
//      unsigned long currentMillis4 = millis();
//      if (currentMillis4 - previousMillis4 > interval4)
//      { previousMillis4 = currentMillis4;
//        Shifter.setRegisterPin(4, LOW);
//      }
//      unsigned long currentMillis5 = millis();
//      if (currentMillis5 - previousMillis5 > interval5)
//      { previousMillis5 = currentMillis5;
//        Shifter.setRegisterPin(1, LOW);
//      }
//      unsigned long currentMillis6 = millis();
//      if (currentMillis6 - previousMillis6 > interval6)
//      { previousMillis6 = currentMillis6;
//        Shifter.setRegisterPin(7, LOW);
//      }
//      unsigned long currentMillis7 = millis();
//      if (currentMillis7 - previousMillis7 > interval7)
//      { previousMillis7 = currentMillis7;
//        Shifter.setRegisterPin(3, LOW);
//      }
//      unsigned long currentMillis8 = millis();
//      if (currentMillis8 - previousMillis8 > interval8)
//      { previousMillis8 = currentMillis8;
//        Shifter.setRegisterPin(13, LOW);
//      }
//      unsigned long currentMillis9 = millis();
//      if (currentMillis9 - previousMillis9 > interval9)
//      { previousMillis9 = currentMillis9;
//        Shifter.setRegisterPin(10, HIGH);
//      }
    }
    else if (temp1 < setTmp && temp1 > setTmp - 1 && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=22%E");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, LOW);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, LOW);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else if (temp1 < setTmp && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=33%E");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, LOW);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, HIGH);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }

    }
    else
    { lcd.setCursor(9, 0);
      lcd.print(" P=0%E ");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, LOW);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, LOW);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, LOW);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, LOW);
      }
    }
  }
  
  ////////////////////////////////////////////////////////////////////////////////////////////////////////////
  else if (eco == 66&&on_off==1) {
    if (temp1 < setTmp && temp1 > setTmp - 0.5 && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=11%E");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, LOW);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, LOW);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, LOW);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else if (temp1 < setTmp && temp1 > setTmp - 1 && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=22%E");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, LOW);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, LOW);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else if (temp1 < setTmp && temp1 > setTmp - 1.5 && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=33%E");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, LOW);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, HIGH);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }

    }
    else if (temp1 < setTmp && temp1 > setTmp - 2 && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=44%E");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, HIGH);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, HIGH);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else if (temp1 < setTmp && temp1 > setTmp - 2.5 && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=55%E");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, HIGH);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, HIGH);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, HIGH);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else if (temp1 < setTmp && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=66%E");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, HIGH);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, HIGH);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, HIGH);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, HIGH);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else
    { lcd.setCursor(9, 0);
      lcd.print(" P=0%E ");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, LOW);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, LOW);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, LOW);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, LOW);
      }
    }
  }
  
  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  else if(eco==0&&on_off==1)  {
    if (temp1 < setTmp && temp1 > setTmp - 0.5 && bar1 > -1 && bar1 < 3&&on_off==1)
    { lcd.setCursor(9, 0);
      lcd.print(" P=11% ");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, LOW);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, LOW);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, LOW);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else if (temp1 < setTmp && temp1 > setTmp - 1 && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=22% ");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, LOW);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, LOW);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else if (temp1 < setTmp && temp1 > setTmp - 1.5 && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=33% ");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, LOW);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, HIGH);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }

    }
    else if (temp1 < setTmp && temp1 > setTmp - 2 && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=44% ");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, HIGH);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, HIGH);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else if (temp1 < setTmp && temp1 > setTmp - 2.5 && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=55% ");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, HIGH);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, HIGH);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, HIGH);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else if (temp1 < setTmp && temp1 > setTmp - 3 && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=66% ");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, HIGH);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, HIGH);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, HIGH);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, HIGH);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else if (temp1 < setTmp && temp1 > setTmp - 3.5 && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=77% ");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, HIGH);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, HIGH);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, HIGH);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, HIGH);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, HIGH);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else if (temp1 < setTmp && temp1 > setTmp - 4 && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=88% ");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, HIGH);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, HIGH);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, HIGH);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, HIGH);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, HIGH);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, HIGH);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else if ( temp1 < setTmp && bar1 > -1 && bar1 < 3)
    { lcd.setCursor(9, 0);
      lcd.print(" P=100%");
      Shifter.setRegisterPin(5, HIGH);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, HIGH);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, HIGH);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, HIGH);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, HIGH);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, HIGH);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, HIGH);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, HIGH);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, HIGH);
      }
    }
    else
    { lcd.setCursor(9, 0);
      lcd.print(" P=0%  ");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, LOW);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, LOW);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, LOW);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, LOW);
      }
    }
  }
    else if (on_off==0)
    { lcd.setCursor(9, 0);
      lcd.print(" P=0  ");
      Shifter.setRegisterPin(5, LOW);
      unsigned long currentMillis2 = millis();
      if (currentMillis2 - previousMillis2 > interval2)
      { previousMillis2 = currentMillis2;
        Shifter.setRegisterPin(2, LOW);
      }
      unsigned long currentMillis3 = millis();
      if (currentMillis3 - previousMillis3 > interval3)
      { previousMillis3 = currentMillis3;
        Shifter.setRegisterPin(9, LOW);
      }
      unsigned long currentMillis4 = millis();
      if (currentMillis4 - previousMillis4 > interval4)
      { previousMillis4 = currentMillis4;
        Shifter.setRegisterPin(4, LOW);
      }
      unsigned long currentMillis5 = millis();
      if (currentMillis5 - previousMillis5 > interval5)
      { previousMillis5 = currentMillis5;
        Shifter.setRegisterPin(1, LOW);
      }
      unsigned long currentMillis6 = millis();
      if (currentMillis6 - previousMillis6 > interval6)
      { previousMillis6 = currentMillis6;
        Shifter.setRegisterPin(7, LOW);
      }
      unsigned long currentMillis7 = millis();
      if (currentMillis7 - previousMillis7 > interval7)
      { previousMillis7 = currentMillis7;
        Shifter.setRegisterPin(3, LOW);
      }
      unsigned long currentMillis8 = millis();
      if (currentMillis8 - previousMillis8 > interval8)
      { previousMillis8 = currentMillis8;
        Shifter.setRegisterPin(13, LOW);
      }
      unsigned long currentMillis9 = millis();
      if (currentMillis9 - previousMillis9 > interval9)
      { previousMillis9 = currentMillis9;
        Shifter.setRegisterPin(10, LOW);
      }
    }
  
 
  ///////////////////////////////////////////////////////////////////////////////////////////////////////

  // Опрос клавиатуры
  int Feature = ReadKey(KEYPAD_PIN);

  //Включение подсветки
  if (Feature == 1 )
  {
    backlightStatus = 1;
    digitalWrite(BACKLIGHT_PIN, backlightStatus);
  }

  //Отключение подсветки
  if (Feature == 2 )
  {
    backlightStatus = 0;
    digitalWrite(BACKLIGHT_PIN, backlightStatus);
  }

  //Переход к редактированию заданной температуры
  if (Feature == 5 )
  { delay(200); setTemperature();
  }
  //Переход к редактированию еко режима
  if (Feature == 3 )
  { delay(200); ecoRegim();
  }
   //Переход к включению\выключению котла
  if (Feature == 4 )
  { delay(200); boilerStart();
  }
}

Для начала, полный список того, что я поменял в программе:

  1. Блок констант и одна глобальная переменная (строки 302-306)
  2. Две функции setupHeaters (строки 308-313) и realSetupHeaters (строки 315-323)
  3. Вызов функции realSetupHeaters (строки 330-331)
  4. Пример вызова функции setupHeaters (строки 382-386)
  5. Также, я закомментировал много строк (387 – 429).

Больше я не менял ничего.

Прочитайте мой комментарий в строке 381 и поступите также во всех остальных местах, т.е. вместо Ваших длинных кусков, вставьте мой кусок с вызовом функции setupHeaters. Таких длинных кусков у Вас в программе аж 22 (если я не ошибся. Я поменял только один. Поменяйте остальные по образу и подобию (см. комментарии в строках 383-385).

У Вас 9 тэнов. Я их нумерую с 0-го по 8-ой. Номера пинов, соответствующие тэнам определены в строке 306. Т.е. 0-ой тэн у нас на пине 5, 1-ый – на пине 2, второй – на пине 9 и т.д.

Теперь давайте о логике работы.

Самое важное здесь это переменная allTenStates (строка 302). Она всегда в соответствующих битах содержит желаемое состояние пинов соответствующих тэнов (именно желаемое, а не реальное – это важно!). Т.е. если в нулевом бите 1, в первом 0, а во втором снова 1, это значит, что логика Вашей программы хочет чтобы пины тэнов 0 и 2 (пины 5 и 9) были в HIGH, а пин тэна 1 (пин 2) – в LOW. Повторяю, в этой переменной содержатся ЖЕЛАЕМЫЕ состояния пинов. Они могут совпадать с реальными, а могут и не совпадать. В этом вся фишка.

Функция setupHeaters (строки 382-386) как раз устанавливает эти желаемые состояния. Она вызывается из Вашей логики (пример вызова в строках 382-386, остальные вызовы допишете сами). Она выводит нужную строку на экран и устанавливает желаемые состояния. Её можно вызывать сколь угодно часто. Она никак не завязана на время, т.к. она ничего не делает с реальными пинами. Она лишь устанавливает их желаемое состояние.

С этой функцией всё понятно? Её цель – обеспечить, чтобы переменная allTenStates всегда содержала правильное, самое последнее – актуальное желаемое состояние пинов.

Теперь переходим к функции realSetupHeaters (строки 330-331). Она должна обязательно вызываться при каждом проходе loop (я делаю это в строке 331) и ей передаётся параметр – текущее значение millis (чтобы ей лишний раз не запрашивать).

Она чётко делится на три части.

Первая часть (строки 316 – 318) – отвечает за то, что бы остальные части работали строго раз в 3 секунды (на самом деле временной интервал задан в константе TEN_OPERATION_INTERVAL – строка 304). Если интервал ещё не истёк, она возвращает управление в loop (строка 318).

Вторая часть (строки 319-320) считает номер тэна который в этот раз будем включать/выключать и помещает его в переменную. currentTen. Этот номер равен остатку от деления «количества пошедших с начала работы программы трехсекундных интервалов» на количество тэнов. Т.е. в самом начале мы обслуживаем тэн 0, через 3 секунды – тэн 1, через три секунды – тэн 2 и т.д.. После тэна 8, через 3 секунды мы снова обслужим тэн 0.

Наконец, третья часть (строки 321-322) приводит состояние пина текущего тэна в соответствие с «желаемым», которое берёт из переменной allTenStates. Если он и так уже был в нужном состоянии – ничего страшного. Ну был он HIGH, а мы его ещё раз в HIGH перевели – хуже не будет – ещё HIGH’ее он не станет.

Вот и вся логика функции realSetupHeaters

Теперь Вы понимаете общий замысел. Мы отделили логику принятия решений от их (решений) исполнения. Решения принимает Ваш длинны if-else-if-… моя функция setupHeaters их (решения) просто записывает для хранения, а функция realSetupHeaters независимо от того когда решения приняты, просто исполняет их строго по своему расписанию.

Такой приём – «отделение логики принятия решений» от «исполнения решений» - очень частая вещь в архитектуре программ. Это позволяет чётко резать программы на независящие друг от друга куски. Например, один кусок ставит запросы в очередь на обработку, а обработчик - обрабатывает. Первый кусок вообще не знает что там делается с запросами - он их только в очередь ставит, а второй понятия не имеет откуда они в очереди берутся. Зато менеджер процессов может наблюдать за очередью и если она растёт - запустить дополнительный обработчик. а если иссякла - загнуть один их обработчиков - нефиг ресурсы жрать. Это вообще нормальная практика.

Разумеется при такой логике работы, если мы включили (уже реально включили) какой-то тэн, а логический блок буквально через миллискунду передумал и приказал его выключить, реально он выключится только тогда, когда до него дойдёт очередь, т.к. через 27 секунд. Но я заранее спросил Вас, устраивает ли Вас такой подход, так что «кушайте теперь» :))))

Ну, ладно, если чего неясно – спрашивайте.

P.S. У меня нет Вашей схемы, и проверить я не могу. Вроде всё нормально, но если где лопухнулся-таки, Вы опишите повнятнее затык. Подумаем, может попрошу Вас куда-нибудь отладочную печать поставить – разберёмся.

sergey555
Offline
Зарегистрирован: 21.09.2016

Крутняк!!:)

Спасибо Евгений!!

Разложили как на пальцах! Практически даже все понял, несмотря на мой мизерный опыт!

Переписал код аналогично Вашему примеру, и вот что получилось:

компилятор выдал ошибку "'EEPROM' was not declared in this scope" и указал на строку 297 (также на все  подобные строки)

Вы  их тоже изменяли, да?

С чем это может быть связано?

sergey555
Offline
Зарегистрирован: 21.09.2016

Разобрался, у меня была подключена не та библиотека. Поменял но теперь выскочила следующая ошибка "expression cannot be used as a function" на строке 303.

Это уже не могу разобрать(((

ЕвгенийП
ЕвгенийП аватар
Offline
Зарегистрирован: 25.05.2015

sergey555 пишет:

компилятор выдал ошибку "'EEPROM' was not declared in this scope" и указал на строку 297 (также на все  подобные строки)

Вы  их тоже изменяли, да?

С чем это может быть связано?

Простите, забыл сказать. У меня другая библиотека епрома и чтобы скомпилировать код я поменял все вызовы.

1. Верните свою библиотеку, что была и

2. сделайте замену типа "Заменить все" вот таким образом

2.1 EEPROM.write везде замените на EEPROM_write_byte

2.2 EEPROM.read везде замените на EEPROM_read_byte
 
 
Простите, забыл
 
-------------
 
Если будут ещё ошики, Вы новый тескт выложите. а то там номера строк уже поменялись.
sergey555
Offline
Зарегистрирован: 21.09.2016

// Термометр будет подключен на Pin 0
#include <EEPROM.h> // Подключаем библиотеку для работы с ARDUINO EEPROM
#include <LiquidCrystal.h>
#include <OneWire.h> // Подключаем библиотеку для работы с шиной OneWire
#include <DallasTemperature.h>//Подключаем библиотеку для работы с термометром66
#include <Shift595.h>              // подключим библиотеку для работы со здвиговыми регистрами


// обьявим модуль для работы с здвиговыми регистрами
#define   dataPin           3      // pin 14 on the 74HC595
#define   latchPin          1      // pin 12 on the 74HC595
#define   clockPin          2      // pin 11 on the 74HC595
#define   numOfRegisters    2      // количество регистров сдвига 
Shift595 Shifter(dataPin, latchPin, clockPin, numOfRegisters);

LiquidCrystal lcd(8, 9, 4, 5, 6, 7); //Подключаем LCD-дисплей

// создаем переменные для определения давления в системе отопления
float analogSens = A1; //Подключаем датчик давления к аналоговому выводу А1
float bar;    //создаем переменную давления в барылях
float val = analogRead(analogSens);;
float bar1;// переменная для хранения состояния давления
boolean on_off = 0;//переменная для хранения состояния включения котла
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
OneWire oneWire(0);
DallasTemperature sensors(&oneWire);//Создаем объект sensors, подключенный по OneWire

//Создаем переменные для работы с термометром
DeviceAddress tempDeviceAddress;  //переменная для хранения адреса датчика

//Define Variables we'll be connecting to
//double Setpoint, Input, Output;

float temp1 = 0; //переменная для текущего значения температуры
int setTmp = 0; // переменная для заданного значения температуры
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

int eco = 0; //....................................................................................................
int eco33 = 33;
int eco66 = 66;

//Подсветка управляется через пин D10
#define BACKLIGHT_PIN 10
//Создаем переменную для хранения состояния подсветки
boolean backlightStatus = 1;


//Объявим переменные для задания задержки измерения температуры
long previousMillis1 = 0;
long interval1 = 1000; // интервал опроса датчиков температуры

// Объявим переменные для задания задержки включения реле нагревателей
long previousMillis2 = 0;  //----------------------------------------------------------------------------------
long interval2 = 3000;
long previousMillis3 = 0;
long interval3 = 6000;
long previousMillis4 = 0;
long interval4 = 9000;
long previousMillis5 = 0;
long interval5 = 12000;
long previousMillis6 = 0;
long interval6 = 15000;
long previousMillis7 = 0;
long interval7 = 18000;
long previousMillis8 = 0;
long interval8 = 21000;
long previousMillis9 = 0;
long interval9 = 24000;

#define KEYPAD_PIN A0
//Определим значения на аналоговом входе для клавиатуры
#define ButtonUp_LOW 129
#define ButtonUp_HIGH 133
#define ButtonDown_LOW 306
#define ButtonDown_HIGH 311
#define ButtonLeft_LOW 479
#define ButtonLeft_HIGH 483
#define ButtonRight_LOW 0
#define ButtonRight_HIGH 50
#define ButtonSelect_LOW 717
#define ButtonSelect_HIGH 725

void setup()
{
  Shifter.clearRegisters();

  //Считаем из постоянной памяти заданную температуру
  setTmp = EEPROM.read(0); //Заданная температура будет храниться по адресу 0
  sensors.getAddress(tempDeviceAddress, 0);

  //Считаем из постоянной памяти выбраный режим...................................................................
  eco = EEPROM.read(1); //выбраный режим будет храниться по адресу 1

  //Считаем из постоянной памяти состояние включения котла...................................................................
  on_off = EEPROM.read(2); //выбраный режим будет храниться по адресу 2

  //Настроим подсветку дисплея
  pinMode(BACKLIGHT_PIN, OUTPUT);
  digitalWrite(BACKLIGHT_PIN, backlightStatus);

  //Выведем на дисплей стартовое сообщение на 2 секунды
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("ANGELINKA LOVE");
  lcd.setCursor(0, 1);
  lcd.print("      v1.0      ");
  delay(1000);

  // выведем на дисплей заданное значение температуры на 2 секунды
  lcd.setCursor(0, 1);
  lcd.print("  Set temp:     ");
  lcd.setCursor(12, 1);
  lcd.print(setTmp);
  delay(100);

  //Очистим дисплей
  lcd.clear();//lcd.begin(16, 2);
}

//Определим функцию для опроса аналоговой клавиатуры
//Функция опроса клавиатуры, принимает адрес пина, к которому подключена клавиатура, и возвращает код клавиши:
// 1 - UP
// 2 - DOWN
// 3 - LEFT
// 4 - RIGHT
// 5 - SELECT

int ReadKey(int keyPin)
{
  int KeyNum = 0;
  int KeyValue1 = 0;
  int KeyValue2 = 0;

  //Читаем в цикле аналоговый вход, для подавления дребезга и нестабильности
  //читаем по два раза подряд, пока значения не будут равны.
  //Если значения равны 1023 – значит не была нажата ни  одна клавиша.

  do {
    KeyValue1 = analogRead(keyPin);
    KeyValue2 = analogRead(keyPin);
  } while (KeyValue1 == KeyValue2 && KeyValue2 != 1023);

  //Интерпретируем полученное значение и определяем код нажатой клавиши
  if (KeyValue2 < ButtonUp_HIGH && KeyValue2 > ButtonUp_LOW) {
    KeyNum = 1; //Up
  }
  if (KeyValue2 < ButtonDown_HIGH && KeyValue2 > ButtonDown_LOW) {
    KeyNum = 2; //Down
  }
  if (KeyValue2 < ButtonLeft_HIGH && KeyValue2 > ButtonLeft_LOW) {
    KeyNum = 3; //Left
  }
  if (KeyValue2 < ButtonRight_HIGH && KeyValue2 > ButtonRight_LOW) {
    KeyNum = 4; //Right
  }
  if (KeyValue2 < ButtonSelect_HIGH && KeyValue2 > ButtonSelect_LOW) {
    KeyNum = 5; //Select
  }
  //Возвращаем код нажатой клавиши
  return KeyNum;
}

//Определим процедуру редактирования заданной температуры
//Вызывается по нажатию клавиши Select, отображает на дисплее заданную
//температуру и позволяет изменять ее клавишами Up и Down

void setTemperature() {

  int keyCode = 0;

  //выводим на дисплей заданное значение температуры
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("YCTAHOBKA TEMP");
  lcd.setCursor(7, 1);
  lcd.print(setTmp);


  //Опрашиваем клавиатуру, если нажата клавиша Up увеличиваем значение на 1, если Down – уменьшаем на 1
  //Если нажаты клавиши Select или Right – цикл опроса прерывается
  //Задержки введены для борьбы с дребезгом, если клавиши срабатывают четко – можно уменьшить время задержек или вообще их убрать
  do {
    keyCode = ReadKey(KEYPAD_PIN);
    if (keyCode == 1)
    {
      setTmp++;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(setTmp);
    }
    if (keyCode == 2)
    {
      setTmp--;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(setTmp);
    }
  } while (keyCode != 5 && keyCode != 4);
  lcd.clear();
  delay(200);

  //По клавише Select – сохраняем в EEPROM измененное значение
  //По клавише Right – восстанавливаем старое значение
  if (keyCode == 5) {
    EEPROM.write(0, setTmp);
  }
  if (keyCode == 4) {
    setTmp = EEPROM.read(0);
  }
}
void ecoRegim() {
  int keyCode1 = 0;
  //выводим на дисплей выбраный режим
  lcd.begin(16, 2);
  lcd.setCursor(3, 0);
  lcd.print("REGIM ECO");
  lcd.setCursor(7, 1);
  lcd.print(eco);
  lcd.setCursor(9, 1);
  lcd.print('%');

  do {
    keyCode1 = ReadKey(KEYPAD_PIN);
    if (keyCode1 == 1)//включаем еко режим на 33%
    {
      eco = eco33;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(eco);
      lcd.setCursor(9, 1);
      lcd.print('%');
    }
    if (keyCode1 == 2)//включаем еко режим на 66%
    {
      eco = eco66;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(eco);
      lcd.setCursor(9, 1);
      lcd.print('%');
    }
    if (keyCode1 == 4)//отключаем еко режим
    {
      eco = 0;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print("OFF");
    }
  } while (keyCode1 != 3);
  lcd.clear();
  delay(200);

  //По клавише Left – сохраняем в EEPROM измененное значение
  if (keyCode1 == 3) {
    EEPROM.write(1, eco);
  }
}
void boilerStart() {
  int keyCode2 = 0;
  //lcd.clear();//lcd.begin(16, 2);
  //выводим на дисплей заданное значение температуры
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("COCTOYANIE KOTLA");
  lcd.setCursor(7, 1);
  lcd.print(on_off);


  //Опрашиваем клавиатуру, если нажата клавиша Up увеличиваем значение на 1, если Down – уменьшаем на 1
  //Если нажаты клавиши Select или Right – цикл опроса прерывается
  //Задержки введены для борьбы с дребезгом, если клавиши срабатывают четко – можно уменьшить время задержек или вообще их убрать
  do {
    keyCode2 = ReadKey(KEYPAD_PIN);
    if (keyCode2 == 4 && on_off == 0)
    {
      on_off = 1;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(on_off);
      // while(on_off==1);
    }
    if (keyCode2 == 3 && on_off == 1)
    {
      on_off = 0;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(on_off);
      //while(on_off==0);
    }
  } while (keyCode2 != 5);
  lcd.clear();
  delay(200);

  //По клавише Select – сохраняем в EEPROM измененное значение
  //По клавише Right – восстанавливаем старое значение
  if (keyCode2 == 5) {
    EEPROM.write(2, on_off);
  }
}

//#define CURSOR(top, bottom) (((top) << 8) | (bottom))
static uint16_t  allTenStates = 0;
#define TEN(x) ((uint16_t) <<1 (x))  // Маска тена. 1 в нулевом бите - нулевой тэн, в 1-ом - 1-ый и т.д.
#define TEN_OPERATION_INTERVAL  3000UL  // Реальные операции с тенами не чаще (в мс) и только по одному тэну
#define TOTAL_TENS  9UL // Всего тэнов
#define TEN_PINS  { 5, 2, 9, 4, 1, 7, 3, 13, 10 } // номера пинов для тэнов (тэны подряд с 0-го по 8-ой)

static void setupHeaters(const char * title, const uint16_t toLow, const uint16_t toHigh) {
  lcd.setCursor(9, 0);
  lcd.print(title);
  allTenStates |= toHigh;
  allTenStates &= ~toHigh;
}

static void realSetupHeaters(const unsigned long currMillis) {
  static unsigned long intervalCounter = -1;
  const unsigned long threeSecsInterval = currMillis / TEN_OPERATION_INTERVAL;
  if (threeSecsInterval == intervalCounter) return;
  intervalCounter = threeSecsInterval;
  const uint8_t currentTen = (intervalCounter % TOTAL_TENS);
  static const int8_t tenPins[] = TEN_PINS;
  Shifter.setRegisterPin(tenPins[currentTen], (allTenStates & TEN(currentTen)) ? HIGH : LOW);
}

void loop() {
  //Модуль опроса датчика температуры и получения сведений о температуре
  //Вызывается 1 раз в секунду
  unsigned long currentMillis1 = millis();

  // Выполнить реальные операции с тэнами, если пришло время.
  realSetupHeaters(currentMillis1);

  if (currentMillis1 - previousMillis1 > interval1)
  {
    previousMillis1 = currentMillis1;
    //Запуск процедуры измерения температуры
    sensors.setWaitForConversion(false);
    sensors.requestTemperatures();
    sensors.setWaitForConversion(true);

    // delay(50); // задержка для обработки информации внутри термометра, в данном случае можно не задавать

    //Считывание значения температуры
    sensors.getAddress(tempDeviceAddress, 0);
    temp1 = sensors.getTempC(tempDeviceAddress);
    // Вывод текущего значения температуры на дисплей
    lcd.setCursor(0, 0);
    lcd.print("TEMP");
    lcd.setCursor(5, 0);
    lcd.print(temp1);
    lcd.setCursor(0, 1);
    lcd.print("sTEMP");
    lcd.setCursor(6, 1);
    lcd.print(setTmp);

  }
  // создаем модуль считывания значения с датчика давления в системе и конвертации в барыль
  {
    //int sensorBar = analogRead(analogPin1); //создаем переменную для чтения показаний датчика и читаем показания
    // float bar = sensorBar*5./1024.*2.; //преобразуем показания датчика в барыли
    //delay(100);

    val = analogRead(analogSens);
    val = constrain (val, 60,  700);
    bar = map(val, 60, 700, 0, 45);
    bar1 = bar / 10;
    lcd.setCursor(9, 1);
    lcd.print("BAR");
    lcd.setCursor(13, 1);
    lcd.print(bar1);
  }


  /////////////////////////////////////////////////////////////////////////////////////////////////////////////
  //Проверка условия включения/выключения нагревателя

  ////////////////////////////////////////////////////////////////////////////////////////////////////////////
  if (eco == 33 && on_off == 1) {
    if (temp1 < setTmp && temp1 > setTmp - 0.5 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=11%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7), /* в какие тены записать LOW */
        TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 1 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=22%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) , /* в какие тены записать LOW */
        TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 1.5 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=33%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5)  , /* в какие тены записать LOW */
        TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }

    else
    { // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=0 %E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) TEN(6) | TEN(7) |  TEN(8) , /* в какие тены записать LOW */
        /* в какие тены записать HIGH */
      );
    }
  }

  ////////////////////////////////////////////////////////////////////////////////////////////////////////////
  else if (eco == 66 && on_off == 1) {
    if (temp1 < setTmp && temp1 > setTmp - 0.5 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=11%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7), /* в какие тены записать LOW */
        TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 1 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=22%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) , /* в какие тены записать LOW */
        TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 1.5 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=33%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5)  , /* в какие тены записать LOW */
        TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 2 && bar1 > -1 && bar1 < 3) {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=44%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4)   , /* в какие тены записать LOW */
        TEN(5) | TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 2.5 && bar1 > -1 && bar1 < 3) {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=55%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3), /* в какие тены записать LOW */
        TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && bar1 > -1 && bar1 < 3) {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=66%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) , /* в какие тены записать LOW */
        TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=0 %E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8) , /* в какие тены записать LOW */
        /* в какие тены записать HIGH */
      );
    }
  }
  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  else if (eco == 0 && on_off == 1)  {
    if (temp1 < setTmp && temp1 > setTmp - 0.5 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=11%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7), /* в какие тены записать LOW */
        TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 1 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=22%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) , /* в какие тены записать LOW */
        TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 1.5 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=33%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5)  , /* в какие тены записать LOW */
        TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 2 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=44%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4)   , /* в какие тены записать LOW */
        TEN(5) | TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 2.5 && bar1 > -1 && bar1 < 3) {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=55%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3), /* в какие тены записать LOW */
        TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && bar1 > -1 && bar1 < 3) {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=66%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) , /* в какие тены записать LOW */
        TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 3.5 && bar1 > -1 && bar1 < 3)
    { // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=77%E",  /* что выводить на экран */
        TEN(0) | TEN(1) , /* в какие тены записать LOW */
        TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 4 && bar1 > -1 && bar1 < 3)
    { // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=88%E",  /* что выводить на экран */
        TEN(0) , /* в какие тены записать LOW */
        TEN1 | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if ( temp1 < setTmp && bar1 > -1 && bar1 < 3)
    { // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=100%E",  /* что выводить на экран */
                                                                                       , /* в какие тены записать LOW */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else
    { // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=0 %E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8), /* в какие тены записать LOW */
                                                                                        /* в какие тены записать HIGH */
      );
    }
  }
  else (on_off == 0)
  { // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
    setupHeaters(
      " P=0 %E",  /* что выводить на экран */
      TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8), /* в какие тены записать LOW */

      /* в какие тены записать HIGH */
    );
  }



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

  // Опрос клавиатуры
  int Feature = ReadKey(KEYPAD_PIN);

  //Включение подсветки
  if (Feature == 1 )
  {
    backlightStatus = 1;
    digitalWrite(BACKLIGHT_PIN, backlightStatus);
  }

  //Отключение подсветки
  if (Feature == 2 )
  {
    backlightStatus = 0;
    digitalWrite(BACKLIGHT_PIN, backlightStatus);
  }

  //Переход к редактированию заданной температуры
  if (Feature == 5 )
  { delay(200); setTemperature();
  }
  //Переход к редактированию еко режима
  if (Feature == 3 )
  { delay(200); ecoRegim();
  }
  //Переход к включению\выключению котла
  if (Feature == 4 )
  { delay(200); boilerStart();
  }
}

 

sergey555
Offline
Зарегистрирован: 21.09.2016

Вот что получилось

Сейчас ошибка в 303й строке, но я там переставил единицу и больше той ошибки не выдает компилятор! Проверьте пожалуйста, правильно ли я сделал.

Но еще вылезла ошибка в  строке 563 "expected primary-expression before ')' token"

ЕвгенийП
ЕвгенийП аватар
Offline
Зарегистрирован: 25.05.2015

Строка 563 - Вы удалили третий параметр вызова функции. Если не нужен - поставьте 0, но удалять нельзя. Тоже проо строку 411 и про 570. Может ещё где, смотрите (если что сообщение выдаст).

В 303 строке 1 убирайте, там всё правильно, ошибка наведённая. Должно быть

#define TEN(x) ((uint16_t)1 << (x))

Где-то Вы использовали TEN без скобок или с пустыми скобками. Найти пока не могу, нашёл только в строке 546 у Вас TEN1 вместо TEN1 - но это должна быть самостоятельная ошибка.

Кстати, про наведённые ошибки, если бы Вы скопипастили сообщение полностью, было бы видно откуда она вылзла. Впредь копипастите пожалуйста блок сообщений целиком (выделите и Ctrl+C скажите).

В общем исправляйте всё, что я написал. Если будут ошибки, снова выкладывайте и код и ошибки, но посмотрю я их только завтра утром.

sergey555
Offline
Зарегистрирован: 21.09.2016
Поисправлял, и ошибка та же d cnhjrt303
 
Arduino: 1.6.11 (Windows 10), Плата:"Arduino/Genuino Uno"
 
D:\arduino-1.6.11\arduino-builder -dump-prefs -logger=machine -hardware D:\arduino-1.6.11\hardware -tools D:\arduino-1.6.11\tools-builder -tools D:\arduino-1.6.11\hardware\tools\avr -built-in-libraries D:\arduino-1.6.11\libraries -libraries C:\Users\Сергей\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=0X2341_0X0043 -ide-version=10611 -build-path C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp -warnings=more -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avrdude.path=D:\arduino-1.6.11\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=D:\arduino-1.6.11\hardware\tools\avr -verbose C:\Users\Сергей\Documents\Arduino\KOTEL_3_NEN_S_PID_REGULATOROM\TEST2\TEST2.ino
D:\arduino-1.6.11\arduino-builder -compile -logger=machine -hardware D:\arduino-1.6.11\hardware -tools D:\arduino-1.6.11\tools-builder -tools D:\arduino-1.6.11\hardware\tools\avr -built-in-libraries D:\arduino-1.6.11\libraries -libraries C:\Users\Сергей\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=0X2341_0X0043 -ide-version=10611 -build-path C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp -warnings=more -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avrdude.path=D:\arduino-1.6.11\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=D:\arduino-1.6.11\hardware\tools\avr -verbose C:\Users\Сергей\Documents\Arduino\KOTEL_3_NEN_S_PID_REGULATOROM\TEST2\TEST2.ino
Using board 'uno' from platform in folder: D:\arduino-1.6.11\hardware\arduino\avr
Using core 'arduino' from platform in folder: D:\arduino-1.6.11\hardware\arduino\avr
Detecting libraries used...
"D:\arduino-1.6.11\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-ID:\arduino-1.6.11\hardware\arduino\avr\cores\arduino" "-ID:\arduino-1.6.11\hardware\arduino\avr\variants\standard" "C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp\sketch\TEST2.ino.cpp" -o "nul"
"D:\arduino-1.6.11\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-ID:\arduino-1.6.11\hardware\arduino\avr\cores\arduino" "-ID:\arduino-1.6.11\hardware\arduino\avr\variants\standard" "-ID:\arduino-1.6.11\hardware\arduino\avr\libraries\EEPROM\src" "C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp\sketch\TEST2.ino.cpp" -o "nul"
"D:\arduino-1.6.11\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-ID:\arduino-1.6.11\hardware\arduino\avr\cores\arduino" "-ID:\arduino-1.6.11\hardware\arduino\avr\variants\standard" "-ID:\arduino-1.6.11\libraries\LiquidCrystal\src" "-ID:\arduino-1.6.11\hardware\arduino\avr\libraries\EEPROM\src" "C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp\sketch\TEST2.ino.cpp" -o "nul"
"D:\arduino-1.6.11\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-ID:\arduino-1.6.11\hardware\arduino\avr\cores\arduino" "-ID:\arduino-1.6.11\hardware\arduino\avr\variants\standard" "-ID:\arduino-1.6.11\hardware\arduino\avr\libraries\EEPROM\src" "-ID:\arduino-1.6.11\libraries\LiquidCrystal\src" "-ID:\arduino-1.6.11\libraries\OneWire" "C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp\sketch\TEST2.ino.cpp" -o "nul"
"D:\arduino-1.6.11\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-ID:\arduino-1.6.11\hardware\arduino\avr\cores\arduino" "-ID:\arduino-1.6.11\hardware\arduino\avr\variants\standard" "-ID:\arduino-1.6.11\libraries\DallasTemperature" "-ID:\arduino-1.6.11\hardware\arduino\avr\libraries\EEPROM\src" "-ID:\arduino-1.6.11\libraries\LiquidCrystal\src" "-ID:\arduino-1.6.11\libraries\OneWire" "C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp\sketch\TEST2.ino.cpp" -o "nul"
"D:\arduino-1.6.11\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-ID:\arduino-1.6.11\hardware\arduino\avr\cores\arduino" "-ID:\arduino-1.6.11\hardware\arduino\avr\variants\standard" "-ID:\arduino-1.6.11\libraries\OneWire" "-ID:\arduino-1.6.11\libraries\DallasTemperature" "-ID:\arduino-1.6.11\libraries\Shift595" "-ID:\arduino-1.6.11\hardware\arduino\avr\libraries\EEPROM\src" "-ID:\arduino-1.6.11\libraries\LiquidCrystal\src" "C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp\sketch\TEST2.ino.cpp" -o "nul"
"D:\arduino-1.6.11\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-ID:\arduino-1.6.11\hardware\arduino\avr\cores\arduino" "-ID:\arduino-1.6.11\hardware\arduino\avr\variants\standard" "-ID:\arduino-1.6.11\hardware\arduino\avr\libraries\EEPROM\src" "-ID:\arduino-1.6.11\libraries\LiquidCrystal\src" "-ID:\arduino-1.6.11\libraries\OneWire" "-ID:\arduino-1.6.11\libraries\DallasTemperature" "-ID:\arduino-1.6.11\libraries\Shift595" "D:\arduino-1.6.11\libraries\LiquidCrystal\src\LiquidCrystal.cpp" -o "nul"
"D:\arduino-1.6.11\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-ID:\arduino-1.6.11\hardware\arduino\avr\cores\arduino" "-ID:\arduino-1.6.11\hardware\arduino\avr\variants\standard" "-ID:\arduino-1.6.11\libraries\LiquidCrystal\src" "-ID:\arduino-1.6.11\libraries\OneWire" "-ID:\arduino-1.6.11\libraries\DallasTemperature" "-ID:\arduino-1.6.11\libraries\Shift595" "-ID:\arduino-1.6.11\hardware\arduino\avr\libraries\EEPROM\src" "D:\arduino-1.6.11\libraries\OneWire\OneWire.cpp" -o "nul"
"D:\arduino-1.6.11\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-ID:\arduino-1.6.11\hardware\arduino\avr\cores\arduino" "-ID:\arduino-1.6.11\hardware\arduino\avr\variants\standard" "-ID:\arduino-1.6.11\libraries\LiquidCrystal\src" "-ID:\arduino-1.6.11\libraries\OneWire" "-ID:\arduino-1.6.11\libraries\DallasTemperature" "-ID:\arduino-1.6.11\libraries\Shift595" "-ID:\arduino-1.6.11\hardware\arduino\avr\libraries\EEPROM\src" "D:\arduino-1.6.11\libraries\DallasTemperature\DallasTemperature.cpp" -o "nul"
"D:\arduino-1.6.11\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-ID:\arduino-1.6.11\hardware\arduino\avr\cores\arduino" "-ID:\arduino-1.6.11\hardware\arduino\avr\variants\standard" "-ID:\arduino-1.6.11\libraries\DallasTemperature" "-ID:\arduino-1.6.11\libraries\Shift595" "-ID:\arduino-1.6.11\hardware\arduino\avr\libraries\EEPROM\src" "-ID:\arduino-1.6.11\libraries\LiquidCrystal\src" "-ID:\arduino-1.6.11\libraries\OneWire" "D:\arduino-1.6.11\libraries\Shift595\Shift595.cpp" -o "nul"
"D:\arduino-1.6.11\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-ID:\arduino-1.6.11\hardware\arduino\avr\cores\arduino" "-ID:\arduino-1.6.11\hardware\arduino\avr\variants\standard" "-ID:\arduino-1.6.11\libraries\Shift595" "-ID:\arduino-1.6.11\hardware\arduino\avr\libraries\EEPROM\src" "-ID:\arduino-1.6.11\libraries\LiquidCrystal\src" "-ID:\arduino-1.6.11\libraries\OneWire" "-ID:\arduino-1.6.11\libraries\DallasTemperature" "C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp\sketch\TEST2.ino.cpp" -o "nul"
Generating function prototypes...
"D:\arduino-1.6.11\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-ID:\arduino-1.6.11\hardware\arduino\avr\cores\arduino" "-ID:\arduino-1.6.11\hardware\arduino\avr\variants\standard" "-ID:\arduino-1.6.11\hardware\arduino\avr\libraries\EEPROM\src" "-ID:\arduino-1.6.11\libraries\LiquidCrystal\src" "-ID:\arduino-1.6.11\libraries\OneWire" "-ID:\arduino-1.6.11\libraries\DallasTemperature" "-ID:\arduino-1.6.11\libraries\Shift595" "C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp\sketch\TEST2.ino.cpp" -o "C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp\preproc\ctags_target_for_gcc_minus_e.cpp"
"D:\arduino-1.6.11\tools-builder\ctags\5.8-arduino10/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp\preproc\ctags_target_for_gcc_minus_e.cpp"
Компиляция скетча...
"D:\arduino-1.6.11\hardware\tools\avr/bin/avr-g++" -c -g -Os -Wall -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-ID:\arduino-1.6.11\hardware\arduino\avr\cores\arduino" "-ID:\arduino-1.6.11\hardware\arduino\avr\variants\standard" "-ID:\arduino-1.6.11\hardware\arduino\avr\libraries\EEPROM\src" "-ID:\arduino-1.6.11\libraries\LiquidCrystal\src" "-ID:\arduino-1.6.11\libraries\OneWire" "-ID:\arduino-1.6.11\libraries\DallasTemperature" "-ID:\arduino-1.6.11\libraries\Shift595" "C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp\sketch\TEST2.ino.cpp" -o "C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp\sketch\TEST2.ino.cpp.o"
C:\Users\Сергей\Documents\Arduino\KOTEL_3_NEN_S_PID_REGULATOROM\TEST2\TEST2.ino: In function 'void loop()':
 
C:\Users\Сергей\Documents\Arduino\KOTEL_3_NEN_S_PID_REGULATOROM\TEST2\TEST2.ino:333:40: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
 
TEST2:303: error: expression cannot be used as a function
 
C:\Users\Сергей\Documents\Arduino\KOTEL_3_NEN_S_PID_REGULATOROM\TEST2\TEST2.ino:411:61: note: in expansion of macro 'TEN'
 
TEST2:546: error: 'TEN1' was not declared in this scope
 
TEST2:567: error: expected ';' before '{' token
 
Несколько библиотек найдено для "EEPROM.h"
 Используется: D:\arduino-1.6.11\hardware\arduino\avr\libraries\EEPROM
Не используется: D:\arduino-1.6.11\libraries\EEPROM
Используем библиотеку EEPROM версии 2.0 из папки: D:\arduino-1.6.11\hardware\arduino\avr\libraries\EEPROM 
Используем библиотеку LiquidCrystal версии 1.0.5 из папки: D:\arduino-1.6.11\libraries\LiquidCrystal 
Используем библиотеку OneWire версии 2.3.2 из папки: D:\arduino-1.6.11\libraries\OneWire 
Используем библиотеку DallasTemperature версии 3.7.6 из папки: D:\arduino-1.6.11\libraries\DallasTemperature 
Используем библиотеку Shift595 в папке: D:\arduino-1.6.11\libraries\Shift595 (legacy)
exit status 1
expression cannot be used as a function
ЕвгенийП
ЕвгенийП аватар
Offline
Зарегистрирован: 25.05.2015

sergey555, вот теперь лучше. не зря Вы копипастили.

Вот смотрите, что написано в сообщении

TEST2:303: error: expression cannot be used as a function
 
C:\Users\Сергей\Documents\Arduino\KOTEL_3_NEN_S_PID_REGULATOROM\TEST2\TEST2.ino:411:61: note: in expansion of macro 'TEN'
 
TEST2:546: error: 'TEN1' was not declared in this scope
 
TEST2:567: error: expected ';' before '{' token

Строки 1 и 3 - это про одно. Дел в том, что была ошибка в строке 411 и из-за неё не смог развернуться макрос в строке 303. Исправьте в 411 и про 303 само уйдёт (наведённая ошибка).

А в 411 у Вас просто прпущена | между TEN(5) и TEN(6).

Со строкй 546 поняно, скобки пропустили.

В строке 567, видимо, 0 забыли вставить и там параметр пропущен.

sergey555
Offline
Зарегистрирован: 21.09.2016
Arduino: 1.6.11 (Windows 10), Плата:"Arduino/Genuino Uno"
 
D:\arduino-1.6.11\arduino-builder -dump-prefs -logger=machine -hardware D:\arduino-1.6.11\hardware -tools D:\arduino-1.6.11\tools-builder -tools D:\arduino-1.6.11\hardware\tools\avr -built-in-libraries D:\arduino-1.6.11\libraries -libraries C:\Users\Сергей\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=0X2341_0X0043 -ide-version=10611 -build-path C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp -warnings=more -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avrdude.path=D:\arduino-1.6.11\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=D:\arduino-1.6.11\hardware\tools\avr -verbose C:\Users\Сергей\Documents\Arduino\KOTEL_3_NEN_S_PID_REGULATOROM\TEST2\TEST2.ino
D:\arduino-1.6.11\arduino-builder -compile -logger=machine -hardware D:\arduino-1.6.11\hardware -tools D:\arduino-1.6.11\tools-builder -tools D:\arduino-1.6.11\hardware\tools\avr -built-in-libraries D:\arduino-1.6.11\libraries -libraries C:\Users\Сергей\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=0X2341_0X0043 -ide-version=10611 -build-path C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp -warnings=more -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avrdude.path=D:\arduino-1.6.11\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=D:\arduino-1.6.11\hardware\tools\avr -verbose C:\Users\Сергей\Documents\Arduino\KOTEL_3_NEN_S_PID_REGULATOROM\TEST2\TEST2.ino
Using board 'uno' from platform in folder: D:\arduino-1.6.11\hardware\arduino\avr
Using core 'arduino' from platform in folder: D:\arduino-1.6.11\hardware\arduino\avr
Detecting libraries used...
"D:\arduino-1.6.11\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-ID:\arduino-1.6.11\hardware\arduino\avr\cores\arduino" "-ID:\arduino-1.6.11\hardware\arduino\avr\variants\standard" "C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp\sketch\TEST2.ino.cpp" -o "nul"
"D:\arduino-1.6.11\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-ID:\arduino-1.6.11\hardware\arduino\avr\cores\arduino" "-ID:\arduino-1.6.11\hardware\arduino\avr\variants\standard" "-ID:\arduino-1.6.11\libraries\EEPROM2" "C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp\sketch\TEST2.ino.cpp" -o "nul"
"D:\arduino-1.6.11\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-ID:\arduino-1.6.11\hardware\arduino\avr\cores\arduino" "-ID:\arduino-1.6.11\hardware\arduino\avr\variants\standard" "-ID:\arduino-1.6.11\libraries\EEPROM2" "-ID:\arduino-1.6.11\libraries\LiquidCrystal\src" "C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp\sketch\TEST2.ino.cpp" -o "nul"
"D:\arduino-1.6.11\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-ID:\arduino-1.6.11\hardware\arduino\avr\cores\arduino" "-ID:\arduino-1.6.11\hardware\arduino\avr\variants\standard" "-ID:\arduino-1.6.11\libraries\LiquidCrystal\src" "-ID:\arduino-1.6.11\libraries\OneWire" "-ID:\arduino-1.6.11\libraries\EEPROM2" "C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp\sketch\TEST2.ino.cpp" -o "nul"
"D:\arduino-1.6.11\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-ID:\arduino-1.6.11\hardware\arduino\avr\cores\arduino" "-ID:\arduino-1.6.11\hardware\arduino\avr\variants\standard" "-ID:\arduino-1.6.11\libraries\EEPROM2" "-ID:\arduino-1.6.11\libraries\LiquidCrystal\src" "-ID:\arduino-1.6.11\libraries\OneWire" "-ID:\arduino-1.6.11\libraries\DallasTemperature" "C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp\sketch\TEST2.ino.cpp" -o "nul"
"D:\arduino-1.6.11\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-ID:\arduino-1.6.11\hardware\arduino\avr\cores\arduino" "-ID:\arduino-1.6.11\hardware\arduino\avr\variants\standard" "-ID:\arduino-1.6.11\libraries\EEPROM2" "-ID:\arduino-1.6.11\libraries\LiquidCrystal\src" "-ID:\arduino-1.6.11\libraries\OneWire" "-ID:\arduino-1.6.11\libraries\DallasTemperature" "-ID:\arduino-1.6.11\libraries\Shift595" "C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp\sketch\TEST2.ino.cpp" -o "nul"
"D:\arduino-1.6.11\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-ID:\arduino-1.6.11\hardware\arduino\avr\cores\arduino" "-ID:\arduino-1.6.11\hardware\arduino\avr\variants\standard" "-ID:\arduino-1.6.11\libraries\Shift595" "-ID:\arduino-1.6.11\libraries\EEPROM2" "-ID:\arduino-1.6.11\libraries\LiquidCrystal\src" "-ID:\arduino-1.6.11\libraries\OneWire" "-ID:\arduino-1.6.11\libraries\DallasTemperature" "D:\arduino-1.6.11\libraries\EEPROM2\EEPROM2.cpp" -o "nul"
"D:\arduino-1.6.11\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-ID:\arduino-1.6.11\hardware\arduino\avr\cores\arduino" "-ID:\arduino-1.6.11\hardware\arduino\avr\variants\standard" "-ID:\arduino-1.6.11\libraries\EEPROM2" "-ID:\arduino-1.6.11\libraries\LiquidCrystal\src" "-ID:\arduino-1.6.11\libraries\OneWire" "-ID:\arduino-1.6.11\libraries\DallasTemperature" "-ID:\arduino-1.6.11\libraries\Shift595" "D:\arduino-1.6.11\libraries\LiquidCrystal\src\LiquidCrystal.cpp" -o "nul"
"D:\arduino-1.6.11\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-ID:\arduino-1.6.11\hardware\arduino\avr\cores\arduino" "-ID:\arduino-1.6.11\hardware\arduino\avr\variants\standard" "-ID:\arduino-1.6.11\libraries\EEPROM2" "-ID:\arduino-1.6.11\libraries\LiquidCrystal\src" "-ID:\arduino-1.6.11\libraries\OneWire" "-ID:\arduino-1.6.11\libraries\DallasTemperature" "-ID:\arduino-1.6.11\libraries\Shift595" "D:\arduino-1.6.11\libraries\OneWire\OneWire.cpp" -o "nul"
"D:\arduino-1.6.11\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-ID:\arduino-1.6.11\hardware\arduino\avr\cores\arduino" "-ID:\arduino-1.6.11\hardware\arduino\avr\variants\standard" "-ID:\arduino-1.6.11\libraries\EEPROM2" "-ID:\arduino-1.6.11\libraries\LiquidCrystal\src" "-ID:\arduino-1.6.11\libraries\OneWire" "-ID:\arduino-1.6.11\libraries\DallasTemperature" "-ID:\arduino-1.6.11\libraries\Shift595" "D:\arduino-1.6.11\libraries\DallasTemperature\DallasTemperature.cpp" -o "nul"
"D:\arduino-1.6.11\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-ID:\arduino-1.6.11\hardware\arduino\avr\cores\arduino" "-ID:\arduino-1.6.11\hardware\arduino\avr\variants\standard" "-ID:\arduino-1.6.11\libraries\EEPROM2" "-ID:\arduino-1.6.11\libraries\LiquidCrystal\src" "-ID:\arduino-1.6.11\libraries\OneWire" "-ID:\arduino-1.6.11\libraries\DallasTemperature" "-ID:\arduino-1.6.11\libraries\Shift595" "D:\arduino-1.6.11\libraries\Shift595\Shift595.cpp" -o "nul"
"D:\arduino-1.6.11\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-ID:\arduino-1.6.11\hardware\arduino\avr\cores\arduino" "-ID:\arduino-1.6.11\hardware\arduino\avr\variants\standard" "-ID:\arduino-1.6.11\libraries\Shift595" "-ID:\arduino-1.6.11\libraries\EEPROM2" "-ID:\arduino-1.6.11\libraries\LiquidCrystal\src" "-ID:\arduino-1.6.11\libraries\OneWire" "-ID:\arduino-1.6.11\libraries\DallasTemperature" "C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp\sketch\TEST2.ino.cpp" -o "nul"
Generating function prototypes...
"D:\arduino-1.6.11\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-ID:\arduino-1.6.11\hardware\arduino\avr\cores\arduino" "-ID:\arduino-1.6.11\hardware\arduino\avr\variants\standard" "-ID:\arduino-1.6.11\libraries\LiquidCrystal\src" "-ID:\arduino-1.6.11\libraries\OneWire" "-ID:\arduino-1.6.11\libraries\DallasTemperature" "-ID:\arduino-1.6.11\libraries\Shift595" "-ID:\arduino-1.6.11\libraries\EEPROM2" "C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp\sketch\TEST2.ino.cpp" -o "C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp\preproc\ctags_target_for_gcc_minus_e.cpp"
"D:\arduino-1.6.11\tools-builder\ctags\5.8-arduino10/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp\preproc\ctags_target_for_gcc_minus_e.cpp"
Компиляция скетча...
"D:\arduino-1.6.11\hardware\tools\avr/bin/avr-g++" -c -g -Os -Wall -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-ID:\arduino-1.6.11\hardware\arduino\avr\cores\arduino" "-ID:\arduino-1.6.11\hardware\arduino\avr\variants\standard" "-ID:\arduino-1.6.11\libraries\LiquidCrystal\src" "-ID:\arduino-1.6.11\libraries\OneWire" "-ID:\arduino-1.6.11\libraries\DallasTemperature" "-ID:\arduino-1.6.11\libraries\Shift595" "-ID:\arduino-1.6.11\libraries\EEPROM2" "C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp\sketch\TEST2.ino.cpp" -o "C:\Users\D899~1\AppData\Local\Temp\build0e6bdba691b7e6dec752abc2e59c920f.tmp\sketch\TEST2.ino.cpp.o"
C:\Users\Сергей\Documents\Arduino\KOTEL_3_NEN_S_PID_REGULATOROM\TEST2\TEST2.ino: In function 'void loop()':
 
C:\Users\Сергей\Documents\Arduino\KOTEL_3_NEN_S_PID_REGULATOROM\TEST2\TEST2.ino:315:40: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
 
TEST2:285: error: expression cannot be used as a function
 
C:\Users\Сергей\Documents\Arduino\KOTEL_3_NEN_S_PID_REGULATOROM\TEST2\TEST2.ino:393:61: note: in expansion of macro 'TEN'
 
Используем библиотеку EEPROM2 в папке: D:\arduino-1.6.11\libraries\EEPROM2 (legacy)
Используем библиотеку LiquidCrystal версии 1.0.5 из папки: D:\arduino-1.6.11\libraries\LiquidCrystal 
Используем библиотеку OneWire версии 2.3.2 из папки: D:\arduino-1.6.11\libraries\OneWire 
Используем библиотеку DallasTemperature версии 3.7.6 из папки: D:\arduino-1.6.11\libraries\DallasTemperature 
Используем библиотеку Shift595 в папке: D:\arduino-1.6.11\libraries\Shift595 (legacy)
exit status 1
expression cannot be used as a function

 

sergey555
Offline
Зарегистрирован: 21.09.2016
// Термометр будет подключен на Pin 0
#include <EEPROM2.h> // Подключаем библиотеку для работы с ARDUINO EEPROM
#include <LiquidCrystal.h>
#include <OneWire.h> // Подключаем библиотеку для работы с шиной OneWire
#include <DallasTemperature.h>//Подключаем библиотеку для работы с термометром66
#include <Shift595.h>              // подключим библиотеку для работы со здвиговыми регистрами


// обьявим модуль для работы с здвиговыми регистрами
#define   dataPin           3      // pin 14 on the 74HC595
#define   latchPin          1      // pin 12 on the 74HC595
#define   clockPin          2      // pin 11 on the 74HC595
#define   numOfRegisters    2      // количество регистров сдвига 
Shift595 Shifter(dataPin, latchPin, clockPin, numOfRegisters);

LiquidCrystal lcd(8, 9, 4, 5, 6, 7); //Подключаем LCD-дисплей

// создаем переменные для определения давления в системе отопления
float analogSens = A1; //Подключаем датчик давления к аналоговому выводу А1
float bar;    //создаем переменную давления в барылях
float val = analogRead(analogSens);;
float bar1;// переменная для хранения состояния давления
boolean on_off = 0;//переменная для хранения состояния включения котла
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
OneWire oneWire(0);
DallasTemperature sensors(&oneWire);//Создаем объект sensors, подключенный по OneWire

//Создаем переменные для работы с термометром
DeviceAddress tempDeviceAddress;  //переменная для хранения адреса датчика

//Define Variables we'll be connecting to
//double Setpoint, Input, Output;

float temp1 = 0; //переменная для текущего значения температуры
int setTmp = 0; // переменная для заданного значения температуры
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

int eco = 0; //....................................................................................................
int eco33 = 33;
int eco66 = 66;

//Подсветка управляется через пин D10
#define BACKLIGHT_PIN 10
//Создаем переменную для хранения состояния подсветки
boolean backlightStatus = 1;


//Объявим переменные для задания задержки измерения температуры
long previousMillis1 = 0;
long interval1 = 1000; // интервал опроса датчиков температуры

#define KEYPAD_PIN A0
//Определим значения на аналоговом входе для клавиатуры
#define ButtonUp_LOW 129
#define ButtonUp_HIGH 133
#define ButtonDown_LOW 306
#define ButtonDown_HIGH 311
#define ButtonLeft_LOW 479
#define ButtonLeft_HIGH 483
#define ButtonRight_LOW 0
#define ButtonRight_HIGH 50
#define ButtonSelect_LOW 717
#define ButtonSelect_HIGH 725

void setup()
{
  Shifter.clearRegisters();

  //Считаем из постоянной памяти заданную температуру
  setTmp = EEPROM_read_byte(0); //Заданная температура будет храниться по адресу 0
  sensors.getAddress(tempDeviceAddress, 0);

  //Считаем из постоянной памяти выбраный режим...................................................................
  eco = EEPROM_read_byte(1); //выбраный режим будет храниться по адресу 1

  //Считаем из постоянной памяти состояние включения котла...................................................................
  on_off = EEPROM_read_byte(2); //выбраный режим будет храниться по адресу 2

  //Настроим подсветку дисплея
  pinMode(BACKLIGHT_PIN, OUTPUT);
  digitalWrite(BACKLIGHT_PIN, backlightStatus);

  //Выведем на дисплей стартовое сообщение на 2 секунды
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("ANGELINKA LOVE");
  lcd.setCursor(0, 1);
  lcd.print("      v1.0      ");
  delay(1000);

  // выведем на дисплей заданное значение температуры на 2 секунды
  lcd.setCursor(0, 1);
  lcd.print("  Set temp:     ");
  lcd.setCursor(12, 1);
  lcd.print(setTmp);
  delay(100);

  //Очистим дисплей
  lcd.clear();//lcd.begin(16, 2);
}

//Определим функцию для опроса аналоговой клавиатуры
//Функция опроса клавиатуры, принимает адрес пина, к которому подключена клавиатура, и возвращает код клавиши:
// 1 - UP
// 2 - DOWN
// 3 - LEFT
// 4 - RIGHT
// 5 - SELECT

int ReadKey(int keyPin)
{
  int KeyNum = 0;
  int KeyValue1 = 0;
  int KeyValue2 = 0;

  //Читаем в цикле аналоговый вход, для подавления дребезга и нестабильности
  //читаем по два раза подряд, пока значения не будут равны.
  //Если значения равны 1023 – значит не была нажата ни  одна клавиша.

  do {
    KeyValue1 = analogRead(keyPin);
    KeyValue2 = analogRead(keyPin);
  } while (KeyValue1 == KeyValue2 && KeyValue2 != 1023);

  //Интерпретируем полученное значение и определяем код нажатой клавиши
  if (KeyValue2 < ButtonUp_HIGH && KeyValue2 > ButtonUp_LOW) {
    KeyNum = 1; //Up
  }
  if (KeyValue2 < ButtonDown_HIGH && KeyValue2 > ButtonDown_LOW) {
    KeyNum = 2; //Down
  }
  if (KeyValue2 < ButtonLeft_HIGH && KeyValue2 > ButtonLeft_LOW) {
    KeyNum = 3; //Left
  }
  if (KeyValue2 < ButtonRight_HIGH && KeyValue2 > ButtonRight_LOW) {
    KeyNum = 4; //Right
  }
  if (KeyValue2 < ButtonSelect_HIGH && KeyValue2 > ButtonSelect_LOW) {
    KeyNum = 5; //Select
  }
  //Возвращаем код нажатой клавиши
  return KeyNum;
}

//Определим процедуру редактирования заданной температуры
//Вызывается по нажатию клавиши Select, отображает на дисплее заданную
//температуру и позволяет изменять ее клавишами Up и Down

void setTemperature() {

  int keyCode = 0;

  //выводим на дисплей заданное значение температуры
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("YCTAHOBKA TEMP");
  lcd.setCursor(7, 1);
  lcd.print(setTmp);


  //Опрашиваем клавиатуру, если нажата клавиша Up увеличиваем значение на 1, если Down – уменьшаем на 1
  //Если нажаты клавиши Select или Right – цикл опроса прерывается
  //Задержки введены для борьбы с дребезгом, если клавиши срабатывают четко – можно уменьшить время задержек или вообще их убрать
  do {
    keyCode = ReadKey(KEYPAD_PIN);
    if (keyCode == 1)
    {
      setTmp++;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(setTmp);
    }
    if (keyCode == 2)
    {
      setTmp--;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(setTmp);
    }
  } while (keyCode != 5 && keyCode != 4);
  lcd.clear();
  delay(200);

  //По клавише Select – сохраняем в EEPROM измененное значение
  //По клавише Right – восстанавливаем старое значение
  if (keyCode == 5) {
    EEPROM_write_byte(0, setTmp);
  }
  if (keyCode == 4) {
    setTmp = EEPROM_read_byte(0);
  }
}
void ecoRegim() {
  int keyCode1 = 0;
  //выводим на дисплей выбраный режим
  lcd.begin(16, 2);
  lcd.setCursor(3, 0);
  lcd.print("REGIM ECO");
  lcd.setCursor(7, 1);
  lcd.print(eco);
  lcd.setCursor(9, 1);
  lcd.print('%');

  do {
    keyCode1 = ReadKey(KEYPAD_PIN);
    if (keyCode1 == 1)//включаем еко режим на 33%
    {
      eco = eco33;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(eco);
      lcd.setCursor(9, 1);
      lcd.print('%');
    }
    if (keyCode1 == 2)//включаем еко режим на 66%
    {
      eco = eco66;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(eco);
      lcd.setCursor(9, 1);
      lcd.print('%');
    }
    if (keyCode1 == 4)//отключаем еко режим
    {
      eco = 0;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print("OFF");
    }
  } while (keyCode1 != 3);
  lcd.clear();
  delay(200);

  //По клавише Left – сохраняем в EEPROM измененное значение
  if (keyCode1 == 3) {
    EEPROM_write_byte(1, eco);
  }
}
void boilerStart() {
  int keyCode2 = 0;
  //lcd.clear();//lcd.begin(16, 2);
  //выводим на дисплей заданное значение температуры
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("COCTOYANIE KOTLA");
  lcd.setCursor(7, 1);
  lcd.print(on_off);


  //Опрашиваем клавиатуру, если нажата клавиша Up увеличиваем значение на 1, если Down – уменьшаем на 1
  //Если нажаты клавиши Select или Right – цикл опроса прерывается
  //Задержки введены для борьбы с дребезгом, если клавиши срабатывают четко – можно уменьшить время задержек или вообще их убрать
  do {
    keyCode2 = ReadKey(KEYPAD_PIN);
    if (keyCode2 == 4 && on_off == 0)
    {
      on_off = 1;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(on_off);
      // while(on_off==1);
    }
    if (keyCode2 == 3 && on_off == 1)
    {
      on_off = 0;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(on_off);
      //while(on_off==0);
    }
  } while (keyCode2 != 5);
  lcd.clear();
  delay(200);

  //По клавише Select – сохраняем в EEPROM измененное значение
  //По клавише Right – восстанавливаем старое значение
  if (keyCode2 == 5) {
    EEPROM_write_byte(2, on_off);
  }
}

//#define CURSOR(top, bottom) (((top) << 8) | (bottom))
static uint16_t  allTenStates = 0;
#define TEN(x) ((uint16_t)1 << (x))  // Маска тена. 1 в нулевом бите - нулевой тэн, в 1-ом - 1-ый и т.д.
#define TEN_OPERATION_INTERVAL  3000UL  // Реальные операции с тенами не чаще (в мс) и только по одному тэну
#define TOTAL_TENS  9UL // Всего тэнов
#define TEN_PINS  { 5, 2, 9, 4, 1, 7, 3, 13, 10 } // номера пинов для тэнов (тэны подряд с 0-го по 8-ой)

static void setupHeaters(const char * title, const uint16_t toLow, const uint16_t toHigh) {
  lcd.setCursor(9, 0);
  lcd.print(title);
  allTenStates |= toHigh;
  allTenStates &= ~toHigh;
}

static void realSetupHeaters(const unsigned long currMillis) {
  static unsigned long intervalCounter = -1;
  const unsigned long threeSecsInterval = currMillis / TEN_OPERATION_INTERVAL;
  if (threeSecsInterval == intervalCounter) return;
  intervalCounter = threeSecsInterval;
  const uint8_t currentTen = (intervalCounter % TOTAL_TENS);
  static const int8_t tenPins[] = TEN_PINS;
  Shifter.setRegisterPin(tenPins[currentTen], (allTenStates & TEN(currentTen)) ? HIGH : LOW);
}

void loop() {
  //Модуль опроса датчика температуры и получения сведений о температуре
  //Вызывается 1 раз в секунду
  unsigned long currentMillis1 = millis();

  // Выполнить реальные операции с тэнами, если пришло время.
  realSetupHeaters(currentMillis1);

  if (currentMillis1 - previousMillis1 > interval1)
  {
    previousMillis1 = currentMillis1;
    //Запуск процедуры измерения температуры
    sensors.setWaitForConversion(false);
    sensors.requestTemperatures();
    sensors.setWaitForConversion(true);

    // delay(50); // задержка для обработки информации внутри термометра, в данном случае можно не задавать

    //Считывание значения температуры
    sensors.getAddress(tempDeviceAddress, 0);
    temp1 = sensors.getTempC(tempDeviceAddress);
    // Вывод текущего значения температуры на дисплей
    lcd.setCursor(0, 0);
    lcd.print("TEMP");
    lcd.setCursor(5, 0);
    lcd.print(temp1);
    lcd.setCursor(0, 1);
    lcd.print("sTEMP");
    lcd.setCursor(6, 1);
    lcd.print(setTmp);

  }
  // создаем модуль считывания значения с датчика давления в системе и конвертации в барыль
  {
    //int sensorBar = analogRead(analogPin1); //создаем переменную для чтения показаний датчика и читаем показания
    // float bar = sensorBar*5./1024.*2.; //преобразуем показания датчика в барыли
    //delay(100);

    val = analogRead(analogSens);
    val = constrain (val, 60,  700);
    bar = map(val, 60, 700, 0, 45);
    bar1 = bar / 10;
    lcd.setCursor(9, 1);
    lcd.print("BAR");
    lcd.setCursor(13, 1);
    lcd.print(bar1);
  }


  /////////////////////////////////////////////////////////////////////////////////////////////////////////////
  //Проверка условия включения/выключения нагревателя

  ////////////////////////////////////////////////////////////////////////////////////////////////////////////
  if (eco == 33 && on_off == 1) {
    if (temp1 < setTmp && temp1 > setTmp - 0.5 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=11%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7), /* в какие тены записать LOW */
        TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 1 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=22%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) , /* в какие тены записать LOW */
        TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 1.5 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=33%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5)  , /* в какие тены записать LOW */
        TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }

    else
    { // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=0 %E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) TEN(6) | TEN(7) |  TEN(8) , /* в какие тены записать LOW */
      0  /* в какие тены записать HIGH */
      );
    }
  }

  ////////////////////////////////////////////////////////////////////////////////////////////////////////////
  else if (eco == 66 && on_off == 1) {
    if (temp1 < setTmp && temp1 > setTmp - 0.5 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=11%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7), /* в какие тены записать LOW */
        TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 1 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=22%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5)| TEN(6) , /* в какие тены записать LOW */
        TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 1.5 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=33%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5)  , /* в какие тены записать LOW */
        TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 2 && bar1 > -1 && bar1 < 3) {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=44%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4), /* в какие тены записать LOW */
        TEN(5) | TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 2.5 && bar1 > -1 && bar1 < 3) {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=55%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3), /* в какие тены записать LOW */
        TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && bar1 > -1 && bar1 < 3) {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=66%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) , /* в какие тены записать LOW */
        TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=0 %E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8) , /* в какие тены записать LOW */
      0  /* в какие тены записать HIGH */
      );
    }
  }
  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  else if (eco == 0 && on_off == 1)  {
    if (temp1 < setTmp && temp1 > setTmp - 0.5 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=11%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7), /* в какие тены записать LOW */
        TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 1 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=22%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) , /* в какие тены записать LOW */
        TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 1.5 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=33%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5)  , /* в какие тены записать LOW */
        TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 2 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=44%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4)   , /* в какие тены записать LOW */
        TEN(5) | TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 2.5 && bar1 > -1 && bar1 < 3) {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=55%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3), /* в какие тены записать LOW */
        TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && bar1 > -1 && bar1 < 3) {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=66%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) , /* в какие тены записать LOW */
        TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 3.5 && bar1 > -1 && bar1 < 3)
    { // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=77%E",  /* что выводить на экран */
        TEN(0) | TEN(1) , /* в какие тены записать LOW */
        TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 4 && bar1 > -1 && bar1 < 3)
    { // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=88%E",  /* что выводить на экран */
        TEN(0) , /* в какие тены записать LOW */
        TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if ( temp1 < setTmp && bar1 > -1 && bar1 < 3)
    { // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=100%E",  /* что выводить на экран */
         0, /* в какие тены записать LOW */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else
    { // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=0 %E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8), /* в какие тены записать LOW */
         0                                                                               /* в какие тены записать HIGH */
      );
    }
  }
  else if (on_off == 0)
  { // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
    setupHeaters(
      " P=0 %E",  /* что выводить на экран */
      TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8), /* в какие тены записать LOW */

     0 /* в какие тены записать HIGH */
    );
  }



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

  // Опрос клавиатуры
  int Feature = ReadKey(KEYPAD_PIN);

  //Включение подсветки
  if (Feature == 1 )
  {
    backlightStatus = 1;
    digitalWrite(BACKLIGHT_PIN, backlightStatus);
  }

  //Отключение подсветки
  if (Feature == 2 )
  {
    backlightStatus = 0;
    digitalWrite(BACKLIGHT_PIN, backlightStatus);
  }

  //Переход к редактированию заданной температуры
  if (Feature == 5 )
  { delay(200); setTemperature();
  }
  //Переход к редактированию еко режима
  if (Feature == 3 )
  { delay(200); ecoRegim();
  }
  //Переход к включению\выключению котла
  if (Feature == 4 )
  { delay(200); boilerStart();
  }
}

 

sergey555
Offline
Зарегистрирован: 21.09.2016

Евгений, все перепроверил и исправил на сколько понимаю!

Но все равно ошибка... не понятная для меня

ЕвгенийП
ЕвгенийП аватар
Offline
Зарегистрирован: 25.05.2015

Сергей, учитесь читать такие сообщения. Вот, смотрите, сообщение в строке 29 (в портянке сообщений) явно наведённое, надо искать рядом другое с упоминанием макроса TEN. Оно как раз в строке 31. Там говорится, что с макросом TEN проблемы в строке 393. Отлично, смотрим в строку 393 программы и видим, что между  TEN(5) и TEN(6) проущена вертикальная черта. Видите? Исправляйте.

sergey555
Offline
Зарегистрирован: 21.09.2016

Евгений учусь и очень стараюсь!! Даже кое что и получается!

Спасибо за Вашу помощь!!!

Все поисправлял и теперь скетч компилируется и загружается на плату! Визуально (на дисплее) все корректно работает, но вот ТЕНы не включаются. Как бы не посылается сигнал команды... все время выключены, при любых условиях.

есче  запутался с кнопкой включения\выключения (строки 254...281). Мне удалось организовать с помощю АЖ трех кнопок, чтобы всего лиш елементарно включить \выключить котел!!((((

Может тоже подскажете ...:) пожалуйста!!

// Термометр будет подключен на Pin 0
#include <EEPROM2.h> // Подключаем библиотеку для работы с ARDUINO EEPROM
#include <LiquidCrystal.h>
#include <OneWire.h> // Подключаем библиотеку для работы с шиной OneWire
#include <DallasTemperature.h>//Подключаем библиотеку для работы с термометром66
#include <Shift595.h>              // подключим библиотеку для работы со здвиговыми регистрами


// обьявим модуль для работы с здвиговыми регистрами
#define   dataPin           3      // pin 14 on the 74HC595
#define   latchPin          1      // pin 12 on the 74HC595
#define   clockPin          2      // pin 11 on the 74HC595
#define   numOfRegisters    2      // количество регистров сдвига 
Shift595 Shifter(dataPin, latchPin, clockPin, numOfRegisters);

LiquidCrystal lcd(8, 9, 4, 5, 6, 7); //Подключаем LCD-дисплей

// создаем переменные для определения давления в системе отопления
float analogSens = A1; //Подключаем датчик давления к аналоговому выводу А1
float bar;    //создаем переменную давления в барылях
float val = analogRead(analogSens);;
float bar1;// переменная для хранения состояния давления
boolean on_off = 0;//переменная для хранения состояния включения котла
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
OneWire oneWire(0);
DallasTemperature sensors(&oneWire);//Создаем объект sensors, подключенный по OneWire

//Создаем переменные для работы с термометром
DeviceAddress tempDeviceAddress;  //переменная для хранения адреса датчика

//Define Variables we'll be connecting to
//double Setpoint, Input, Output;

float temp1 = 0; //переменная для текущего значения температуры
int setTmp = 0; // переменная для заданного значения температуры
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

int eco = 0; //....................................................................................................
int eco33 = 33;
int eco66 = 66;

//Подсветка управляется через пин D10
#define BACKLIGHT_PIN 10
//Создаем переменную для хранения состояния подсветки
boolean backlightStatus = 1;


//Объявим переменные для задания задержки измерения температуры
long previousMillis1 = 0;
long interval1 = 1000; // интервал опроса датчиков температуры

#define KEYPAD_PIN A0
//Определим значения на аналоговом входе для клавиатуры
#define ButtonUp_LOW 129
#define ButtonUp_HIGH 133
#define ButtonDown_LOW 306
#define ButtonDown_HIGH 311
#define ButtonLeft_LOW 470
#define ButtonLeft_HIGH 490
#define ButtonRight_LOW 0
#define ButtonRight_HIGH 50
#define ButtonSelect_LOW 717
#define ButtonSelect_HIGH 725

void setup()
{
  Shifter.clearRegisters();

  //Считаем из постоянной памяти заданную температуру
  setTmp = EEPROM_read_byte(0); //Заданная температура будет храниться по адресу 0
  sensors.getAddress(tempDeviceAddress, 0);

  //Считаем из постоянной памяти выбраный режим...................................................................
  eco = EEPROM_read_byte(1); //выбраный режим будет храниться по адресу 1

  //Считаем из постоянной памяти состояние включения котла...................................................................
  on_off = EEPROM_read_byte(2); //выбраный режим будет храниться по адресу 2

  //Настроим подсветку дисплея
  pinMode(BACKLIGHT_PIN, OUTPUT);
  digitalWrite(BACKLIGHT_PIN, backlightStatus);

  //Выведем на дисплей стартовое сообщение на 2 секунды
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("ANGELINKA LOVE");
  lcd.setCursor(0, 1);
  lcd.print("      v1.0      ");
  delay(1000);

  // выведем на дисплей заданное значение температуры на 2 секунды
  lcd.setCursor(0, 1);
  lcd.print("  Set temp:     ");
  lcd.setCursor(12, 1);
  lcd.print(setTmp);
  delay(100);

  //Очистим дисплей
  lcd.clear();//lcd.begin(16, 2);
}

//Определим функцию для опроса аналоговой клавиатуры
//Функция опроса клавиатуры, принимает адрес пина, к которому подключена клавиатура, и возвращает код клавиши:
// 1 - UP
// 2 - DOWN
// 3 - LEFT
// 4 - RIGHT
// 5 - SELECT

int ReadKey(int keyPin)
{
  int KeyNum = 0;
  int KeyValue1 = 0;
  int KeyValue2 = 0;

  //Читаем в цикле аналоговый вход, для подавления дребезга и нестабильности
  //читаем по два раза подряд, пока значения не будут равны.
  //Если значения равны 1023 – значит не была нажата ни  одна клавиша.

  do {
    KeyValue1 = analogRead(keyPin);
    KeyValue2 = analogRead(keyPin);
  } while (KeyValue1 == KeyValue2 && KeyValue2 != 1023);

  //Интерпретируем полученное значение и определяем код нажатой клавиши
  if (KeyValue2 < ButtonUp_HIGH && KeyValue2 > ButtonUp_LOW) {
    KeyNum = 1; //Up
  }
  if (KeyValue2 < ButtonDown_HIGH && KeyValue2 > ButtonDown_LOW) {
    KeyNum = 2; //Down
  }
  if (KeyValue2 < ButtonLeft_HIGH && KeyValue2 > ButtonLeft_LOW) {
    KeyNum = 3; //Left
  }
  if (KeyValue2 < ButtonRight_HIGH && KeyValue2 > ButtonRight_LOW) {
    KeyNum = 4; //Right
  }
  if (KeyValue2 < ButtonSelect_HIGH && KeyValue2 > ButtonSelect_LOW) {
    KeyNum = 5; //Select
  }
  //Возвращаем код нажатой клавиши
  return KeyNum;
}

//Определим процедуру редактирования заданной температуры
//Вызывается по нажатию клавиши Select, отображает на дисплее заданную
//температуру и позволяет изменять ее клавишами Up и Down

void setTemperature() {

  int keyCode = 0;

  //выводим на дисплей заданное значение температуры
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("YCTAHOBKA TEMP");
  lcd.setCursor(7, 1);
  lcd.print(setTmp);


  //Опрашиваем клавиатуру, если нажата клавиша Up увеличиваем значение на 1, если Down – уменьшаем на 1
  //Если нажаты клавиши Select или Right – цикл опроса прерывается
  //Задержки введены для борьбы с дребезгом, если клавиши срабатывают четко – можно уменьшить время задержек или вообще их убрать
  do {
    keyCode = ReadKey(KEYPAD_PIN);
    if (keyCode == 1)
    {
      setTmp++;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(setTmp);
    }
    if (keyCode == 2)
    {
      setTmp--;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(setTmp);
    }
  } while (keyCode != 5 && keyCode != 4);
  lcd.clear();
  delay(200);

  //По клавише Select – сохраняем в EEPROM измененное значение
  //По клавише Right – восстанавливаем старое значение
  if (keyCode == 5) {
    EEPROM_write_byte(0, setTmp);
  }
  if (keyCode == 4) {
    setTmp = EEPROM_read_byte(0);
  }
}
void ecoRegim() {
  int keyCode1 = 0;
  //выводим на дисплей выбраный режим
  lcd.begin(16, 2);
  lcd.setCursor(3, 0);
  lcd.print("REGIM ECO");
  lcd.setCursor(7, 1);
  lcd.print(eco);
  lcd.setCursor(9, 1);
  lcd.print('%');

  do {
    keyCode1 = ReadKey(KEYPAD_PIN);
    if (keyCode1 == 1)//включаем еко режим на 33%
    {
      eco = eco33;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(eco);
      lcd.setCursor(9, 1);
      lcd.print('%');
    }
    if (keyCode1 == 2)//включаем еко режим на 66%
    {
      eco = eco66;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(eco);
      lcd.setCursor(9, 1);
      lcd.print('%');
    }
    if (keyCode1 == 4)//отключаем еко режим
    {
      eco = 0;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print("OFF");
    }
  } while (keyCode1 != 3);
  lcd.clear();
  delay(200);

  //По клавише Left – сохраняем в EEPROM измененное значение
  if (keyCode1 == 3) {
    EEPROM_write_byte(1, eco);
  }
}
void boilerStart() {
  int keyCode2 = 0;
  //lcd.clear();//lcd.begin(16, 2);
  //выводим на дисплей заданное значение температуры
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("COCTOYANIE KOTLA");
  lcd.setCursor(7, 1);
  lcd.print(on_off);


  //Опрашиваем клавиатуру, если нажата клавиша Up увеличиваем значение на 1, если Down – уменьшаем на 1
  //Если нажаты клавиши Select или Right – цикл опроса прерывается
  //Задержки введены для борьбы с дребезгом, если клавиши срабатывают четко – можно уменьшить время задержек или вообще их убрать
  do {
    keyCode2 = ReadKey(KEYPAD_PIN);
    if (keyCode2 == 4 && on_off == 0)
    {
      on_off = 1;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(on_off);
      // while(on_off==1);
    }
    if (keyCode2 == 3 && on_off == 1)
    {
      on_off = 0;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(on_off);
      //while(on_off==0);
    }
  } while (keyCode2 != 5);
  lcd.clear();
  delay(200);

  //По клавише Select – сохраняем в EEPROM измененное значение
  //По клавише Right – восстанавливаем старое значение
  if (keyCode2 == 5) {
    EEPROM_write_byte(2, on_off);
  }
}

//#define CURSOR(top, bottom) (((top) << 8) | (bottom))
static uint16_t  allTenStates = 0;
#define TEN(x) ((uint16_t)1 << (x))  // Маска тена. 1 в нулевом бите - нулевой тэн, в 1-ом - 1-ый и т.д.
#define TEN_OPERATION_INTERVAL  3000UL  // Реальные операции с тенами не чаще (в мс) и только по одному тэну
#define TOTAL_TENS  9UL // Всего тэнов
#define TEN_PINS  { 5, 2, 9, 4, 1, 7, 3, 13, 10 } // номера пинов для тэнов (тэны подряд с 0-го по 8-ой)

static void setupHeaters(const char * title, const uint16_t toLow, const uint16_t toHigh) {
  lcd.setCursor(9, 0);
  lcd.print(title);
  allTenStates |= toHigh;
  allTenStates &= ~toHigh;
}

static void realSetupHeaters(const unsigned long currMillis) {
  static unsigned long intervalCounter = -1;
  const unsigned long threeSecsInterval = currMillis / TEN_OPERATION_INTERVAL;
  if (threeSecsInterval == intervalCounter) return;
  intervalCounter = threeSecsInterval;
  const uint8_t currentTen = (intervalCounter % TOTAL_TENS);
  static const int8_t tenPins[] = TEN_PINS;
  Shifter.setRegisterPin(tenPins[currentTen], (allTenStates & TEN(currentTen)) ? HIGH : LOW);
}

void loop() {
  //Модуль опроса датчика температуры и получения сведений о температуре
  //Вызывается 1 раз в секунду
  unsigned long currentMillis1 = millis();

  // Выполнить реальные операции с тэнами, если пришло время.
  realSetupHeaters(currentMillis1);

  if (currentMillis1 - previousMillis1 > interval1)
  {
    previousMillis1 = currentMillis1;
    //Запуск процедуры измерения температуры
    sensors.setWaitForConversion(false);
    sensors.requestTemperatures();
    sensors.setWaitForConversion(true);

    // delay(50); // задержка для обработки информации внутри термометра, в данном случае можно не задавать

    //Считывание значения температуры
    sensors.getAddress(tempDeviceAddress, 0);
    temp1 = sensors.getTempC(tempDeviceAddress);
    // Вывод текущего значения температуры на дисплей
    lcd.setCursor(0, 0);
    lcd.print("TEMP");
    lcd.setCursor(5, 0);
    lcd.print(temp1);
    lcd.setCursor(0, 1);
    lcd.print("sTEMP");
    lcd.setCursor(6, 1);
    lcd.print(setTmp);

  }
  // создаем модуль считывания значения с датчика давления в системе и конвертации в барыль
  {
    //int sensorBar = analogRead(analogPin1); //создаем переменную для чтения показаний датчика и читаем показания
    // float bar = sensorBar*5./1024.*2.; //преобразуем показания датчика в барыли
    //delay(100);

    val = analogRead(analogSens);
    val = constrain (val, 60,  700);
    bar = map(val, 60, 700, 0, 45);
    bar1 = bar / 10;
    lcd.setCursor(9, 1);
    lcd.print("BAR");
    lcd.setCursor(13, 1);
    lcd.print(bar1);
  }


  /////////////////////////////////////////////////////////////////////////////////////////////////////////////
  //Проверка условия включения/выключения нагревателя

  ////////////////////////////////////////////////////////////////////////////////////////////////////////////
  if (eco == 33 && on_off == 1) {
    if (temp1 < setTmp && temp1 > setTmp - 0.5 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=11%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7), /* в какие тены записать LOW */
        TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 1 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=22%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) , /* в какие тены записать LOW */
        TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp&& bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=33%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5)  , /* в какие тены записать LOW */
        TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }

    else
    { // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=0 %E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5)| TEN(6) | TEN(7) |  TEN(8) , /* в какие тены записать LOW */
      0  /* в какие тены записать HIGH */
      );
    }
  }

  ////////////////////////////////////////////////////////////////////////////////////////////////////////////
  else if (eco == 66 && on_off == 1) {
    if (temp1 < setTmp && temp1 > setTmp - 0.5 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=11%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7), /* в какие тены записать LOW */
        TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 1 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=22%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5)| TEN(6) , /* в какие тены записать LOW */
        TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 1.5 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=33%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5)  , /* в какие тены записать LOW */
        TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 2 && bar1 > -1 && bar1 < 3) {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=44%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4), /* в какие тены записать LOW */
        TEN(5) | TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 2.5 && bar1 > -1 && bar1 < 3) {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=55%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3), /* в какие тены записать LOW */
        TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && bar1 > -1 && bar1 < 3) {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=66%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) , /* в какие тены записать LOW */
        TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=0 %E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8) , /* в какие тены записать LOW */
      0  /* в какие тены записать HIGH */
      );
    }
  }
  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
   if (eco == 0 && on_off == 1)  {
    if (temp1 < setTmp && temp1 > setTmp - 0.5 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=11% ",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7), /* в какие тены записать LOW */
        TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 1 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=22% ",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) , /* в какие тены записать LOW */
        TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 1.5 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=33%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5)  , /* в какие тены записать LOW */
        TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 2 && bar1 > -1 && bar1 < 3)
    {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=44% ",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4)   , /* в какие тены записать LOW */
        TEN(5) | TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 2.5 && bar1 > -1 && bar1 < 3) {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=55%E",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3), /* в какие тены записать LOW */
        TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp&& temp1 > setTmp - 3 && bar1 > -1 && bar1 < 3) {
      // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=66% ",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) , /* в какие тены записать LOW */
        TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 3.5 && bar1 > -1 && bar1 < 3)
    { // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=77%E",  /* что выводить на экран */
        TEN(0) | TEN(1) , /* в какие тены записать LOW */
        TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if (temp1 < setTmp && temp1 > setTmp - 4 && bar1 > -1 && bar1 < 3)
    { // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=88% ",  /* что выводить на экран */
        TEN(0) , /* в какие тены записать LOW */
        TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else if ( temp1 < setTmp && bar1 > -1 && bar1 < 3)
    { // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=100% ",  /* что выводить на экран */
         0, /* в какие тены записать LOW */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8) /* в какие тены записать HIGH */
      );
    }
    else
    { // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
      setupHeaters(
        " P=0 % ",  /* что выводить на экран */
        TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8), /* в какие тены записать LOW */
         0                                                                               /* в какие тены записать HIGH */
      );
    }
  }
  else if (on_off == 0)
  { // ВМЕСТО ТОГО, ЧТО ЗАКОММЕНТИРОВАНО НИЖЕ, ПИШЕМ ВЫЗОВ ФУНКЦИИ
    setupHeaters(
      " P=0 % ",  /* что выводить на экран */
      TEN(0) | TEN(1) | TEN(2) | TEN(3) | TEN(4) | TEN(5) | TEN(6) | TEN(7) |  TEN(8), /* в какие тены записать LOW */

     0 /* в какие тены записать HIGH */
    );
  }



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

  // Опрос клавиатуры
  int Feature = ReadKey(KEYPAD_PIN);

  //Включение подсветки
  if (Feature == 1 )
  {
    backlightStatus = 1;
    digitalWrite(BACKLIGHT_PIN, backlightStatus);
  }

  //Отключение подсветки
  if (Feature == 2 )
  {
    backlightStatus = 0;
    digitalWrite(BACKLIGHT_PIN, backlightStatus);
  }

  //Переход к редактированию заданной температуры
  if (Feature == 5 )
  { delay(200); setTemperature();
  }
  //Переход к редактированию еко режима
  if (Feature == 3 )
  { delay(200); ecoRegim();
  }
  //Переход к включению\выключению котла
  if (Feature == 4 )
  { delay(200); boilerStart();
  }
}

 

ЕвгенийП
ЕвгенийП аватар
Offline
Зарегистрирован: 25.05.2015

sergey555 пишет:

Визуально (на дисплее) все корректно работает, но вот ТЕНы не включаются. Как бы не посылается сигнал команды... все время выключены, при любых условиях.

Давайте разбираться. Для начала нужно понять, кто виноват. Программа или схема. Как Вы понимаете, программа ничего не включает. Её дело лишь подать HIGH или LOW на нужный пин. Если она подёт правильно, а тэн не включается - это уже вопрос к схеме. Поэтому, давайте выясним правильно ли программа включает пины. Для этого

1) в setup добавьте Serial.begin(...
2) строку 304 закомментируйте (выбрасывать не надо, пригодится ещё)
3) сразу после закомментированной строки 304 вставьте код:

const uint8_t tp = tenPins[currentTen];
const uint8_t hl = (allTenStates & TEN(currentTen)) ? HIGH : LOW;
Serial.print("Pin: ");
Serial.print(tp);
Serial.print("; NewValue:");
Serial.print((hl ? "HIGH" : "LOW");
Serial.print("; allTenStates=");
Serial.println(allTenStates, HEX);
Shifter.setRegisterPin(tp, hl);

(у меня нет под рукой компилятора, так что если какая опечатка, уж поправьте сами).

Теперь, каждый три секунды в Serial будет уходить строка. содержащая номер пина и значение в которое он устанавливается. Проанализируйте, всё ли правильно. 

Если всё правильно, то смотрите схему "почему на пин подаём правильно, а тен не работает". Если же в этом месте пины устанавливаются неправильно, дайте мне копию того, что выводится в сериал монитор (только не картинку, а скопипастите текст) я проверю по битам и поговрим дальше.

sergey555 пишет:

есче  запутался с кнопкой включения\выключения (строки 254...281). Мне удалось организовать с помощю АЖ трех кнопок, чтобы всего лиш елементарно включить \выключить котел!!((((

Может тоже подскажете ...:) пожалуйста!!

Давайте дожмём одно, а потом переключимся.

 

 

sergey555
Offline
Зарегистрирован: 21.09.2016

Вы имеете ввиду пмн на моих здвиговых регистрах?

Просто напомню у меня тены подключены через здивиговые (2) регистры.

С ардуины подаются толь 16 бит

sergey555
Offline
Зарегистрирован: 21.09.2016

Вот что в Serial 

Pin: 2; NewValue:LOW; allTenStates=0

Pin: 9; NewValue:LOW; allTenStates=0

Pin: 4; NewValue:LOW; allTenStates=0

Pin: 1; NewValue:LOW; allTenStates=0

Pin: 7; NewValue:LOW; allTenStates=0

Pin: 3; NewValue:LOW; allTenStates=0

Pin: 13; NewValue:LOW; allTenStates=0

Pin: 10; NewValue:LOW; allTenStates=0

Pin: 5; NewValue:LOW; allTenStates=0

Pin: 2; NewValue:LOW; allTenStates=0

Pin: 9; NewValue:LOW; allTenStates=0

Pin: 4; NewValue:LOW; allTenStates=0

Pin: 1; NewValue:LOW; allTenStates=0

И.Т.Д

 

ЕвгенийП
ЕвгенийП аватар
Offline
Зарегистрирован: 25.05.2015

Блиин!

allTenStates  - всегда 0!

Посмотрите на строки 293-294. Ну, понятно же, что чёртова опечатка!

allTenStates |= toHigh;
allTenStates &= ~toHigh;

Разумеется в нижней должно быть toLow, а не toHigh.

Правьте :)

ЕвгенийП
ЕвгенийП аватар
Offline
Зарегистрирован: 25.05.2015

sergey555 пишет:

Вы имеете ввиду пмн на моих здвиговых регистрах?

Просто напомню у меня тены подключены через здивиговые (2) регистры.

С ардуины подаются толь 16 бит

Это мне без разницы. Постарайтесь перенять эту привычку - всегда четко разделяйте сущности. Без этого системному инженеру не жить.

Вот смотрите, в данный момент мы отлаживаем программу. Программа выставляет пины (чьи они - сейчас нам всё равно). Нас ПОКА вообще не волнует, что просиходит вокруг, до тех порЮ пока мы не будем уверены, что пины выставляются правильно. Тогда, если система не заработает, будем смотреть дальше, но мы уже будем уверены, что пины  выставляются хорошо - это будет наш тыл, точка от которой мы безопасно отталкиваемся. Понимаете, большую систему охватить одним взлядом невозможно. Её надо делить на куски и работать с кусками. А глобальным взлядом охватывать уже крупные куски, но для этого нужно быть в этих кусках стопудово увереным. Вот сейчас мы дожимаем выставление пинов. Печать показала, там есть проблема. Исправим. Если печать покажет, что пины выставляются хорошо, а работать таки не будет, будем смотреть схему и т.п. пока не заработает.

 

sergey555
Offline
Зарегистрирован: 21.09.2016

Евгений все ЗАРАБОТАЛО!!!

Так как вы и описывали!)))

вообще работает так как мне и нужно!!!!

Сасибо огромное чисто человеческое!!!

sergey555
Offline
Зарегистрирован: 21.09.2016

честно говоря я только 2 недели как вообще познакомился с програмированием и ардуиной!! Так что простите, если выгляжу как первокласник! Стараюсь учится и понимать! Но когда Вы мне присылаете куски кодов, я понимаю что вообще ничего не понимаю!! 

ЕвгенийП
ЕвгенийП аватар
Offline
Зарегистрирован: 25.05.2015

Да, незачто, обращайтесь, если что.

sergey555
Offline
Зарегистрирован: 21.09.2016

Та вот по поводу кнопок... Просил есче:)

если можте конечно!

sergey555
Offline
Зарегистрирован: 21.09.2016

есче  запутался с кнопкой включения\выключения (строки 254...281). Мне удалось организовать с помощю АЖ трех кнопок, чтобы всего лиш елементарно включить \выключить котел!!((((

Может тоже подскажете ...:) пожалуйста!!

ЕвгенийП
ЕвгенийП аватар
Offline
Зарегистрирован: 25.05.2015

Могу. только объясните подробно и толково что нужно, и что есть сейчас.

Отвечать я смогу сегодня только от случая к случаю (типа раз в час), а завтра нормально можно будет поработать.

sergey555
Offline
Зарегистрирован: 21.09.2016

Отлично! Так и наберусь пратики хоть чуть!

Вот кусок который управляет вкл\выкл котла

do {
    keyCode2 = ReadKey(KEYPAD_PIN);
    if (keyCode2 == 4 && on_off == 0)
    {
      on_off = 1;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(on_off);
      // while(on_off==1);
    }
    if (keyCode2 == 3 && on_off == 1)
    {
      on_off = 0;
      delay(200);
      lcd.setCursor(7, 1);
      lcd.print(on_off);
      //while(on_off==0);
    }
  } while (keyCode2 != 5);
  lcd.clear();
  delay(200);
//По клавише Select – сохраняем в EEPROM измененное значение
  if (keyCode2 == 5) {
    EEPROM_write_byte(2, on_off);
  }
}

 

Но тут как видите мне нужно сначала нажать кнопку "4" потом кнопку "3" чтобы выключить (логический 0), или снова "4" чтобы включить. После чего кнопкой "5" сохраняю выбраное состояние! Бред конечно!! но так у меня получилось и все(((

Хотелось бы чтобы нажал кнопку "4" - включился котел, нажал есче раз - выключился.

 

qwone
qwone аватар
Offline
Зарегистрирован: 03.07.2016

sergey555 пишет:

Хотелось бы чтобы нажал кнопку "4" - включился котел, нажал есче раз - выключился.

У вас очень много пробелов в знании. Так что с разбегу и нахрапом  не получится.

При загрузке в скетча . EEPROM обнуляется принудительно. Так что нереально одним скечем загузить ЕЕPROM, а потом закоментить запись и работать дальше. Для тестировки и добавление в программу скину вам код.

#include <EEPROM.h>
uint8_t X1 ;
int X2     ;
float X3   ;

void save_eeprom(){
  EEPROM.write(0, 12)    ;// X1
  byte raw[4]            ;
  (int&)raw = 200        ;// X2
  EEPROM.write(1, raw[0]);
  EEPROM.write(2, raw[1]);
  (float&)raw = 23.34    ;// X3 
  EEPROM.write(3, raw[0]);
  EEPROM.write(4, raw[1]);
  EEPROM.write(5, raw[2]);
  EEPROM.write(6, raw[3]);

  }

void load_eeprom(){
  X1=EEPROM.read(0);
  byte raw[4];
  raw[0]=EEPROM.read(1);
  raw[1]=EEPROM.read(2);
  int & XX2 = (int&)raw;
  X2 = XX2;
  raw[0]=EEPROM.read(3);
  raw[1]=EEPROM.read(4);
  raw[2]=EEPROM.read(5);
  raw[3]=EEPROM.read(6);
  float & XX3 = (float&)raw;
  X3 = XX3; 
  }

void setup() {
  save_eeprom();
  load_eeprom();
  Serial.begin(9600);
  Serial.print("X1: ");
  Serial.println(X1);
  Serial.print("X2: ");
  Serial.println(X2);
  Serial.print("X3: ");
  Serial.println(X3);
}
void loop() {
}

 

ЕвгенийП
ЕвгенийП аватар
Offline
Зарегистрирован: 25.05.2015

sergey555 пишет:

Хотелось бы чтобы нажал кнопку "4" - включился котел, нажал есче раз - выключился.

Ну, так и делайте, кто Вам не даёт-то?

keyCode2 = ReadKey(KEYPAD_PIN);	// Читаем что там за кнопка
if (keyCode2 == 4) {	// Если это кнопка 4
	on_off = 1 - on_off;	// Меняем on_off (с 0 на 1 или с 1 на 0)
	EEPROM_write_byte(2, on_off);	// Сохраняем изменённое значение on_off
}

 

sergey555
Offline
Зарегистрирован: 21.09.2016

Здарвствуте Евгений!

Хочу высказать Вам большую благодарность за помощь в реализации моего проекта! Долго не писал о результатах, так как хотел испытать на практике (зима пришла)! Уже болие месяца проект работает отлично!!

За исключением одного момента, который, как оказалось немножко не коректно работает. Его я не упоминал в данной теме, потому что не считал столь важным. Но в итоге получилось так, что на практике етот момент оказался не мение важным.

И так:

Помимо тенов контроллер включает тем же битовым сигналом вводной пускатель и циркуляционный насос.
Получается если ети два "контакта" добавить в виде дополнительных тенов, то они включаются по своей очереди.

А нужно чтобы включение выглядило так : включаем коьел - включается вводной пускатель - через 5 секунд циркуляционный насос - через 5 секунд все тены, согласно настроек.

А когда отключаем котел - выключаются тены, согласно настроек - через 30 секунд выключается циркуляционный насос - через 20 секунд выключается вводной пускатель.

Но есть возможность, перепаяв некоторые ножки на плате котла, устроить управление включением\выключением определенного пина. Но все же важен тот момент, что ети два пина (пускатель и насос) должны включатся \выключатся именно так как я описал выше.

Спасибо большое!!!