////////////////////////////////////////////////////////////////////////////////
// Name:       Waterklok-02 Florigs waterklok 4-kanaals                       //
// http://robotigs.com/robotigs/includes/bots_header.php?idbot=18             //
//             An Arduino Uno is used to switch a relais to output 12 Vdc     //
// Created by: HARB rboek2@gmail.com june 2020 GPL copyrights                 //
// Platform:   Arduino UNO Rev3                                               //
// As outputs the following modules are mounted:                              //
// - Standard Arduino Onboard LED (PWM)                                       //
//           http://robotigs.nl/robotigs/includes/parts_header.php?idpart=185 //
// - 3 color LED (PWM)                                                        //
//           http://robotigs.nl/robotigs/includes/parts_header.php?idpart=293 //
// - Activ loudspeaker / buzzer                                               //
//           http://robotigs.nl/robotigs/includes/parts_header.php?idpart=240 //
// - 220 Vac Relay                                                            //
//           http://robotigs.nl/robotigs/includes/parts_header.php?idpart=189 //
// As inputs the following modules are mounted:                               //
// - DS1307 Real Time Clock                                                   //
//           http://robotigs.nl/robotigs/includes/parts_header.php?idpart=289 //
// - Temp DS18B20                                                             //
//           http://robotigs.nl/robotigs/includes/parts_header.php?idpart=180 //
// - LDR                                                                      //
//           http://robotigs.nl/robotigs/includes/parts_header.php?idpart=46  //
// For communications are mounted:                                            //
// - Standard Serial Monitor output                                           //
//            http://robotigs.nl/robotigs/includes/parts_header.php?idpart=43 //
// - Lan ENC28J60 unit                                                        //
//           http://robotigs.nl/robotigs/includes/parts_header.php?idpart=313 //
////////////////////////////////////////////////////////////////////////////////




////////////////////////////////////////////////////////////////////////////////
// EEPROM MEMORY MAP:                                                         //
// Start End  Number Description                                              //
// 0000  0000      1   Never use this memory location to be AVR compatible    //
// 0001  0001      1   tuinLDRtreshold *10 to switch DAY=0/NIGHT=1023     LDR //
// 0002  0002      1   Number of minutes tuinWaterDelay after dark        ALL //
// 0003  0003      1 WATER1 tuinWater1prog program 1=off 2=on 3=auto   RELAY1 //
// 0004  0004      1   Number of minutes tuinWater1spray water on      RELAY1 //
// 0005  0005      1 WATER2 tuinWater2prog program 1=off 2=on 3=auto   RELAY2 //
// 0006  0006      1   Number of minutes tuinWater2spray water on      RELAY2 //
// 0007  0007      1 WATER3 tuinWater3prog program 1=off 2=on 3=auto   RELAY3 //
// 0008  0008      1   Number of minutes tuinWater3spray water on      RELAY3 //
// 0009  0009      1 WATER4 tuinWater4Pprog program 1=off 2=on 3=auto  RELAY4 //
// 0010  0010      1   Number of minutes tuinWater4spray water on      RELAY4 //
////////////////////////////////////////////////////////////////////////////////




// SET PRECOMPILER OPTIONS *****************************************************
  // Initialse conditional compiling, uncomment to include, comment to exclude -
  // Do comment the next line for runtime versions -----------------------------
  #define RS232                   //Uncomment to include Serial Monitor sections
  //#ifdef RS232     //Only include these lines if the variable has been defined

  //Define the needed header files for the precompiler, no charge if not used --
  #include <Wire.h>                 //Date and time functions using a RTC DS1307
  #include <RTClib.h>                //connected via I2C and Wire lib RTC DS1307
             // http://robotigs.nl/robotigs/includes/parts_header.php?idpart=289

  #include <EEPROM.h>                       //Needed for read or write in EEPROM
             // http://robotigs.nl/robotigs/includes/parts_header.php?idpart=312

  #include <OneWire.h>    //Library can be installed through Arduino IDE DS18B20
             // http://robotigs.nl/robotigs/includes/parts_header.php?idpart=180

  #include <EtherCard.h>          //Small library ment for ethernet LAN ENC28J60
             // http://robotigs.nl/robotigs/includes/parts_header.php?idpart=313


  // Define precompiler variables, runs faster & doesn`t use RAM ---------------
  // Define PINS ---------------------------------------------------------------
  OneWire term1(A0);         //Connects to pin 17, but may be any DIO pin DS1820
  #define ldrPin       A1        //Define to which DA converter pin connects LDR
  #define Relay3Pin    A2       //12Vdc output switch pin connects WATER4 RELAY4
  #define Relay4Pin    A3       //12Vdc output switch pin connects WATER3 RELAY3
  //                    0, 1                 Serial monitor aansluiting TERMINAL
  //#define kCePin      2                                           //RST DS1302
  #define ledRedPin     3         //3 Colour LED, which PWM pin connects RED LED
  #define buzActPin     4          //Define DIO output pin connects ACTIV BUZZER
  #define ledGrePin     5       //3 Colour LED, which PWM pin connects GREEN LED
  #define ledBluPin     6        //3 Colour LED, which PWM pin connects BLUE LED
  #define Relay1Pin     7                                        //WATER1 RELAY1
  #define Relay2Pin     9                                        //WATER2 RELAY2
    //#define SpiCLK    8               //PB0 -- CLK/PCINT0 SPI pin LAN ENC28J60
    //#define SpiSS    10                //PB0 -- CS/PCINT0 SPI pin LAN ENC28J60
    //#define SpiMOSI  11              //PB2 -- MOSI/PCINT2 SPI pin LAN ENC28J60
    //#define SpiMISO  12             //PB3 -- MISO/PCINT3  SPI pin LAN ENC28J60
    //#define SpiSCK   13               //PB1 -- SCK/PCINT1 SPI pin LAN ENC28J60

  //Define EEPROM variables ----------------------------------------------------
  int     tuinLDRprog     =   1;         //DAG/NACHT 1=dag 2=nacht 3=auto RELAY0
  int     tuinLDRtreshold =  40;          //*10 switches DAY=0/NIGHT=1023 RELAY0
  int     tuinLDRdelay    =  10;   //Minutes cool down after getting dark RELAY0
  int     tuinWater1prog  =   1;     //WATER1 program 1=off 2=on 3=auto   RELAY1
  int     tuinWater1spray =  10;             //Number of minutes water on RELAY1
  int     tuinWater2prog  =   1;     //WATER2 program 1=off 2=on 3=auto   RELAY2
  int     tuinWater2spray =  10;             //Number of minutes water on RELAY2
  int     tuinWater3prog  =   1;     //WATER3 program 1=off 2=on 3=auto   RELAY3
  int     tuinWater3spray =  10;             //Number of minutes water on RELAY3
  int     tuinWater4prog  =   1;     //WATER4 program 1=off 2=on 3=auto   RELAY4
  int     tuinWater4spray =  10;             //Number of minutes water on RELAY4

  //Define DATABASE VARIABLES --------------------------------------------------
  float   tuinSoilTemp    =  2.3;   //Soil temperature in Celsius DS18B20 SENSOR
  word    tuinLDR         = 1023;       //Lichtsterkte meting, 0-1023 LDR SENSOR
  bool    tuinDayNight    = HIGH;       //Status HIGH=dag of LOW=nacht DAG/NACHT
  bool    tuinAutoTrigger = LOW; //HIGH=True=program, LOW=False=manual DAG/NACHT
  bool    tuinRelay1      = HIGH;      //Status HIGH=off or LOW=on WATER1 RELAY1
  bool    tuinRelay2      = HIGH;      //Status HIGH=off or LOW=on WATER2 RELAY2
  bool    tuinRelay3      = HIGH;      //Status HIGH=off or LOW=on WATER3 RELAY3
  bool    tuinRelay4      = HIGH;      //Status HIGH=off or LOW=on WATER4 RELAY4

  //Define VARIABLES -----------------------------------------------------------
  bool    ledOnBoardVal  = LOW;  //You choose HIGH=on or LOW=off for LED_BUILTIN
  byte    msWait         =   2;         //Test your patience during the test LED
  byte    brillance      = 128;  //Brightness of any color, just to test PWM LED

  byte    present        = 0;   //Used for oneWire, present = ds.reset() DS18B20
  byte    i;                  //Used for oneWire, loopcounter byte array DS18B20
  byte    data[12];           //Used for oneWire to store data read from DS18B20
  byte    type1_s        = 0;        //Type 0 = ok, except old DS1820=1, DS18B20
  byte    addr1[8];              //Array with first 8 bytes, inc/address DS18B20

  char    zxc[5];            //Needed to convert float to sting for LAN ENC28J60
  static byte mymac[]    = {0x00,0x01,0x02,0x03,0x04,0x05};//Unique LAN ENC28J60
  char    panel          =  '0';//Output unit to perform command on LAN ENC28J60
  char    command        =  '0';  //Command to perform, received by LAN ENC28J60
  char    buf[100];                       //Needed to reply html to LAN ENC28J60
  long    value          =   0;     //Value to process, received by LAN ENC28J60
  byte    value1         =  '0';   //Value least significant bit by LAN ENC28J60
  byte    value2         =  '0';      //Value to store, received by LAN ENC28J60
  byte    value3         =  '0';      //Value to store, received by LAN ENC28J60
  byte    value4         =  '0';    //Value most significant bit by LAN ENC28J60

  word    LDRtreshold    =   0;                   //tuinLDRtreshold times 10 LDR
  long    startPeriod    =   0;           //Minutes start from timer value RELAY
  long    endPeriod      =   0;   //Minutes end of period from timer value RELAY
  long    doneSpraying   =   0;       //Finished automatic run so turn OFF RELAY
  bool    ledBlueVal     =  LOW;     //toggleBlueLed HIGH-on or LOW-off BLUE LED

  int     jaar           = 1991;                   //Read or set the year DS1307
  int     maand          =   12;                  //Read or set the month DS1307
  int     dag            =   31;                    //Read or set the dag DS1307
  int     uur            =   23;                    //Read or set the uur DS1307
  int     minuut         =   59;                 //Read or set the minuut DS1307
  int     seconde        =   59;                //Read or set the seconds DS1307

  word    readCounter    =    0;          //If counted down to zero READ SENSORS
  word    readTimer      = 2000;  //Fill readCounter after reaching zero SENSORS
  word    timerSprinkler =    0;  //Timer resets to zero at Day/Night change LDR
  int     currentMinute  =    0; //If not equal time increase timerSprinkler LDR

  //Initialise objects ---------------------------------------------------------
  byte Ethernet::buffer[600];                                     //LAN ENC28J60
  BufferFiller bfill;                                             //LAN ENC28J60
  DS1307 rtc;                                //Initialize Real Time Clock object
//END OF PRECOMPILER OPTIONS ---------------------------------------------------



void setup() { //Setup runs once ***********************************************
  Serial.begin(115200);    //Nothing more needed for the Serial Monitor TERMINAL
  Serial.println("Setup ports");         //Show the user the setup is done RS232
  pinMode(ledRedPin, OUTPUT);           //Make the LED connection output RED LED
  digitalWrite(ledRedPin, HIGH);                //Notify user: switch on LED RED
  pinMode(ledGrePin, OUTPUT);         //Make the LED connection output GREEN LED
  pinMode(ledBluPin, OUTPUT);          //Make the LED connection output BLUE LED
  pinMode(LED_BUILTIN, OUTPUT);  //Arduino boards contain an onboard BUILTIN LED
  pinMode(buzActPin, OUTPUT);                 //Set this pin as output to BUZZER

  beep(10);                       //Create a test beep with KY-012 active BUZZER
  disable_jtag();         //Disable jtag to free port C, enabled by default JTAG

  //EEPROMfirstTime();               //FACTORY SETTINGS write values into EEPROM
  EEPROMonBoot();         //Everytime time on boot use, write values into EEPROM
  tuinLDRprog     = EEPROM.read( 1);     //DAG/NACHT 1=dag 2=nacht 3=auto RELAY0
  tuinLDRtreshold = EEPROM.read( 2); //*10 to switch DAY=0/NIGHT=1023 LDR RELAY0
  LDRtreshold     = tuinLDRtreshold * 10;        //Working value vs stored value
  tuinLDRdelay    = EEPROM.read( 3);    //Minutes of cool down delay dark RELAY0
  tuinWater1prog  = EEPROM.read( 4);   //WATER1 program 1=off 2=on 3=auto RELAY1
  tuinWater1spray = EEPROM.read( 5);         //Number of minutes water on RELAY1
  tuinWater2prog  = EEPROM.read( 6);   //WATER2 program 1=off 2=on 3=auto RELAY2
  tuinWater2spray = EEPROM.read( 7);         //Number of minutes water on RELAY2
  tuinWater3prog  = EEPROM.read( 8);   //WATER3 program 1=off 2=on 3=auto RELAY3
  tuinWater3spray = EEPROM.read( 9);         //Number of minutes water on RELAY3
  tuinWater4prog  = EEPROM.read(10);   //WATER4 program 1=off 2=on 3=auto RELAY4
  tuinWater4spray = EEPROM.read(11);         //Number of minutes water on RELAY4

  pinMode(Relay1Pin, OUTPUT);         //Arduino boards contain an onboard RELAY1
  digitalWrite(Relay1Pin, tuinRelay1);                 //Switches OFF the RELAY1
  pinMode(Relay2Pin, OUTPUT);         //Arduino boards contain an onboard RELAY2
  digitalWrite(Relay2Pin, tuinRelay2);                 //Switches OFF the RELAY2
  pinMode(Relay3Pin, OUTPUT);         //Arduino boards contain an onboard RELAY3
  digitalWrite(Relay3Pin, tuinRelay3);                 //Switches OFF the RELAY3
  pinMode(Relay4Pin, OUTPUT);         //Arduino boards contain an onboard RELAY4
  digitalWrite(Relay4Pin, tuinRelay4);                 //Switches OFF the RELAY4


  //Start objects --------------------------------------------------------------
  Serial.println("Setup DS1820");        //Show the user the setup is done RS232
  beep(10);                       //Create a test beep with KY-012 active BUZZER
  DS1820_init();      //Determins the type of DS1820 and reads properties DS1820
  Serial.println("Setup TWI");           //Show the user the setup is done RS232
  Wire.begin();                                   //Start the TWI object running 
  Serial.println("Setup DS1037");        //Show the user the setup is done RS232
  rtc.begin();    //Initialize Wire.begin first. Start the object running DS1307
  //rtc.adjust(DateTime(__DATE__, __TIME__));      //Set to time compiled DS1307
  Serial.println("Setup Ethernet");      //Show the user the setup is done RS232
  if (ether.begin(sizeof Ethernet::buffer, mymac) == 0) {         //LAN ENC28J60
    Serial.println(F("Failed to access Ethernet controller"));    //LAN ENC28J60
  } //End of if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)

  Serial.println(F("Setting up DHCP"));                           //LAN ENC28J60
  if (!ether.dhcpSetup()) {                                       //LAN ENC28J60
    Serial.println(F("DHCP failed"));                             //LAN ENC28J60
  } //End of if (!ether.dhcpSetup())

  //Test hardware and software -------------------------------------------------
  Serial.println("Setup2");              //Show the user the setup is done RS232
  show_LAN();                                       //Shows DHCP settings of LAN
  test_LEDs();            //PWM fade in and fade out for all 4 LEDs on board LED
  //test_RELAY();                          //Switches ON for 2 seconds the RELAY
  beep(10);                       //Create a test beep with KY-012 active BUZZER
  autoRelay();                //Switch DAY/NIGHT AND RELAY according to settings
  Serial.println("Setup completed");     //Show the user the setup is done RS232
} //End of setup ---------------------------------------------------------------

static word homePage() { //Setting up internet buffer filler -------------------
  long t = millis() / 1000;
  word h = t / 3600;
  byte m = (t / 60) % 60;
  byte s = t % 60;
  bfill = ether.tcpOffset();
  bfill.emit_p(PSTR(
    "HTTP/1.1 200 OK\r\n"
    "Content-Type: text/html\r\n"
    "Pragma: no-cache\r\n"
    "\r\n"
    "$D $D $D $D $D $D $S $D $D $D $D $D $D $D $D $D $D $D $D $D $D $D $D $D $D\r\n"), 
    jaar,
    maand,
    dag,
    uur,
    minuut,
    seconde,
    
    dtostrf(tuinSoilTemp,3,2,zxc), 
    
    tuinLDR,
    tuinDayNight,
    
    tuinRelay1,
    tuinRelay2,
    tuinRelay3,
    tuinRelay4,

    tuinLDRprog,
    tuinLDRtreshold,
    tuinLDRdelay,
    tuinWater1prog,
    tuinWater1spray,
    tuinWater2prog,
    tuinWater2spray,
    tuinWater3prog,
    tuinWater3spray,
    tuinWater4prog,
    tuinWater4spray,
    timerSprinkler
  );
  return bfill.position();
} //End of Setting up internet buffer filler -----------------------------------




void loop() { //KEEP ON RUNNING THIS LOOP FOREVER ******************************
  readTime();        //Reading the time and format results into variables DS1302
  readSensors();          //Read several sensors at timed intervals only SENSORS
  checkBuffer();              //Check if valid tcp data is received LAN ENC28J60
} //Start loop() again ----------------------- KEEP ON RUNNING THIS LOOP FOREVER




void readTime(){ //Read the time and format results into variables DS1307 ******
  DateTime now = rtc.now();                           //Read clock object DS1307
  jaar = now.year();            //Needed to http respond the right date and time
  maand = now.month();          //Needed to http respond the right date and time
  dag = now.day();              //Needed to http respond the right date and time
  uur = now.hour();             //Needed to http respond the right date and time
  minuut = now.minute();            //Needed to http respond and watering switch
  seconde = now.second();       //Needed to http respond the right date and time
  if (minuut != currentMinute) {      //Indien de volgende minuut is aangebroken
    timerSprinkler++;                    //Zet de timerSprinkler 1 minuut omhoog
    currentMinute = minuut;          //Zet de volgende minuut als huidige minuut
  }  //End of                                       //Minuten zijn gecontroleerd
} //Exit readTime --------------------------------------------------------------





void readSensors() { //Read several sensors at timed intervals only ************
  if (readCounter == 0){       //Only perform measurements if counted down TIMER
    analogWrite(ledGrePin, 5);              //Green HIGH=on, LOW=off activityLED
    tuinLDR = analogRead(ldrPin);                   //Read voltage on pin A2 LDR
    DS1820_read();                //Reads the temperature in Celsius from DS1802
    readCounter  =  readTimer;                         //RESET the counter TIMER
    autoRelay();                      //Switches DAY/NIGHT according to settings
    toggle_ledOnBoard();         //Toggles the LED_BUILTIN  ON or OFF onboardLED
    showSensors();       //Shows current sensor values at serial monitor SENSORS
    digitalWrite(ledGrePin, LOW);            //Blue HIGH=on, LOW=off activityLED
  }else{                                //Meaning counter was not yet zero TIMER
    readCounter--;                        //Decrement of the timer counter TIMER
  } //End of if (moistureCnt1 == 0)Perform measurements if counted down    TIMER
} //Exit readSensors -----------------------------------------------------------





void showSensors(){ //Shows current sensor values ******************************
  Serial.print("Klok=");
  Serial.print(jaar);
  Serial.print("/");
  Serial.print(maand);
  Serial.print("/");
  Serial.print(dag);
  Serial.print(" ");
  Serial.print(uur);
  Serial.print(":");
  Serial.print(minuut);
  Serial.print(":");
  Serial.print(seconde);
  Serial.print(" Ldr=");
  Serial.print(tuinLDR);
  Serial.print(" Temperatuur=");
  Serial.println(tuinSoilTemp);
} //Exit showSensors -----------------------------------------------------------




void checkBuffer() { //Check if valid tcp data is received LAN ENC28J60 ********
  word pos = ether.packetLoop(ether.packetReceive());    //Read and empty buffer
  if (pos) {                               //Check if valid tcp data is received
    digitalWrite(ledBluPin, HIGH);              //BLUE HIGH=on, LOW=off BLUE LED
    Serial.println("Internet request");
    char* incomingData = (char *) Ethernet::buffer + pos;
    if (incomingData[5] != ' '){          //There must be some command available
      panel   = incomingData[7];//Isolate the output panel to perform command on
      command = incomingData[8];//Isolate the command received from the INTERNET
      value1  = incomingData[13] - 48;     //Isolate and calculate the parameter
      value2  = incomingData[12] - 48;         //Isolate and calculate parameter
      value3  = incomingData[11] - 48;         //Isolate and calculate parameter
      value4  = incomingData[10] - 48;         //Isolate and calculate parameter
      value   = (value4*1000) + (value3*100) + (value2*10) + value1;
      Serial.println(value);    //LAN ENC28J60
      Serial.println(" +-");
      Serial.print(incomingData);
      Serial.print("-");
      Serial.print(panel);
      Serial.print("-");
      Serial.print(command);
      Serial.print("-");
      Serial.print(value);
      Serial.println("-+");

      beep(1);                    //Create a test beep with KY-012 active BUZZER
      if (panel=='9'){ //********************** Command panel 9 => 9=DS1307 KLOK
        if (command=='1'){                 //Adjust clock with given time DS1302
          jaar = value;                        //Maak een bruikbare klok setting
          value2  = incomingData[15] - 48;     //Isolate and calculate the month
          value1  = incomingData[16] - 48;
          maand = (value2*10) + value1;
          value2  = incomingData[18] - 48;       //Isolate and calculate the day
          value1  = incomingData[19] - 48;
          dag = (value2*10) + value1;
          value2  = incomingData[21] - 48;      //Isolate and calculate the hour
          value1  = incomingData[22] - 48;
          uur = (value2*10) + value1;
          value2  = incomingData[24] - 48;    //Isolate and calculate the minute
          value1  = incomingData[25] - 48;
          minuut = (value2*10) + value1;
          value2  = incomingData[27] - 48;   //Isolate and calculate the seconds
          value1  = incomingData[28] - 48;
          seconde = (value2*10) + value1;
          //rtc.adjust(DateTime(__DATE__, __TIME__));  //Set to time compiled DS1307
        } //End of if (command=='1')         Adjust clock with given time DS1307
      } //End of if (unit=='9') ---------------- Command unit 9 => 9=DS1307 KLOK
      checkCommand();                   //There should be some command available
    } //End of if (incomingData[5] != ' ')     End of There must be some command
    ether.httpServerReply(homePage());                      //send web page data
    digitalWrite(ledBluPin, LOW);               //BLUE HIGH=on, LOW=off BLUE LED
  } //End of if (pos)                        Check if valid tcp data is received
} //Exit checkBuffer -----------------------------------------------------------




void checkCommand() { //There should be some command available *****************
  tuinAutoTrigger = LOW;         //HIGH=True=program, LOW=False=manual DAG/NACHT
  
  if (panel == '0'){ //********************* Command panel 0 => DAY/NIGHT SWITCH
    if (command == '1'){ //================= Instructie 1 => DAG/NACHT OFF=1=DAY
      tuinLDRprog = 1;                  //0=unknown, 1=off, 2=on, 3=auto, set ON
      timerSprinkler = 0;                  //Reset the sproeier coounter to zero
      EEPROM.write(1, 1);                             //Write 1 byte into EEPROM
      tuinDayNight = 1;                             //Switch DAG/NACHT OFF=1=DAY
      autoRelay();                      //Switch DAY/NIGHT according to settings
    } //End of if (command == '1')             Instructie 1 => DAG/NACHT OFF=DAY

        if (command == '2'){ //============ Instructie 2 => DAG/NACHT ON=0=NIGHT
          tuinLDRprog = 2;              //0=unknown, 1=off, 2=on, 3=auto, set ON
          timerSprinkler = 0;              //Reset the sproeier coounter to zero
          EEPROM.write(1, 2);                         //Write 1 byte into EEPROM
          tuinDayNight = 0;                          //Switch DAG/NACHT ON=0=NIGHT
          autoRelay();                  //Switch DAY/NIGHT according to settings
        } //End of if (command == '2')        Instructie 2 => DAG/NACHT ON=NIGHT

        if (command == '3'){ //================== Instructie 3 => DAG/NACHT AUTO
          tuinLDRprog = 3;              //0=unknown, 1=off, 2=on, 3=auto, set ON
          timerSprinkler = 0;              //Reset the sproeier coounter to zero
          EEPROM.write(1, 3);                         //Write 1 byte into EEPROM
          autoRelay();                  //Switch DAY/NIGHT according to settings
        } //End of if (command == '3')            Instructie 3 => DAG/NACHT AUTO

        if (command == '4'){ //====== Instructie 4 => SET LDR TRESHOLD DAY/NIGHT
          tuinLDRtreshold = value;          //Valude to switch from day to night
          LDRtreshold = value * 10;              //Working value vs stored value
          EEPROM.write(2, tuinLDRtreshold);           //Write 1 byte into EEPROM
          autoRelay();                  //Switch DAY/NIGHT according to settings
        } //End of if (command == '4') Instructie 4 => SET LDR RESHOLD DAY/NIGHT

        if (command == '5'){ //=========== Instructie 5 => SET COOL DOWN MINUTES
          tuinLDRdelay = value;             //Valude to switch from day to night
          EEPROM.write(3, tuinLDRdelay);              //Write 1 byte into EEPROM
          autoRelay();                  //Switch DAY/NIGHT according to settings
        } //End of if (command == '5')     Instructie 5 => SET COOL DOWN MINUTES
      } //End of if (unit == '0') ---- End of Command unit 0 => DAY/NIGHT SWITCH



      if (panel == '1'){ //***************** Command panel 1 => RELAY1 SPROEIER1
        if (command == '1'){ //=================== Instructie 1 => SPROEIER1 OFF
          tuinWater1prog = 1;           //0=unknown, 1=off, 2=on, 3=auto, set ON
          EEPROM.write(4, 1);                         //Write 1 byte into EEPROM
          tuinRelay1 = 1;                              //Set SPROEIER1 OFF=1=UIT
          digitalWrite(Relay1Pin, 1);               //Switch SPROEIER1 OFF=1=UIT
          //autoRelay();                  //Switch DAY/NIGHT according to settings
        } //End of if (command == '1')             Instructie 1 => SPROEIER1 OFF

        if (command == '2'){ //==================== Instructie 2 => SPROEIER1 ON
          tuinWater1prog = 2;           //0=unknown, 1=off, 2=on, 3=auto, set ON
          EEPROM.write(4, 2);                         //Write 1 byte into EEPROM
          tuinRelay1 = 0;                               //Set SPROEIER1 ON=1=AAN
          digitalWrite(Relay1Pin, 0);                //Switch SPROEIER1 ON=1=AAN
          //autoRelay();                  //Switch DAY/NIGHT according to settings
        } //End of if (command == '2'){             Instructie 2 => SPROEIER1 ON

        if (command == '3'){ //================== Instructie 3 => SPROEIER1 AUTO
          tuinWater1prog = 3;           //0=unknown, 1=off, 2=on, 3=auto, set ON
          EEPROM.write(4, 3);                         //Write 1 byte into EEPROM
          autoRelay();           //Switch sprinkler ON/OFF according to settings
        } //End of if (command == '3'){           Instructie 3 => SPROEIER1 AUTO

        if (command == '4'){ //======== Instructie 4 => SET SPROEITIJD SPROEIER1
          tuinWater1spray = value;          //Valude to switch from day to night
          EEPROM.write(5, tuinWater1spray);           //Write 1 byte into EEPROM
          autoRelay();           //Switch sprinkler ON/OFF according to settings
        } //End of if (command == '4')  Instructie 4 => SET SPROEITIJD SPROEIER1
      } //End of if (unit == '1') -------------- End of Command unit 1 => RELAY1


      if (panel == '2'){ //***************** Command panel 2 => RELAY2 SPROEIER2
        if (command == '1'){ //=================== Instructie 1 => SPROEIER2 OFF
          tuinWater2prog = 1;           //0=unknown, 1=off, 2=on, 3=auto, set ON
          EEPROM.write(6, 1);                         //Write 1 byte into EEPROM
          tuinRelay2 = 1;                              //Set SPROEIER2 OFF=1=UIT
          digitalWrite(Relay2Pin, 1);               //Switch SPROEIER2 OFF=1=UIT
        } //End of if (command == '1')             Instructie 1 => SPROEIER2 OFF

        if (command == '2'){ //==================== Instructie 2 => SPROEIER2 ON
          tuinWater2prog = 2;           //0=unknown, 1=off, 2=on, 3=auto, set ON
          EEPROM.write(6, 2);                         //Write 1 byte into EEPROM
          tuinRelay2 = 0;                               //Set SPROEIER2 ON=1=AAN
          digitalWrite(Relay2Pin, 0);                //Switch SPROEIER2 ON=1=AAN
        } //End of if (command == '2'){             Instructie 2 => SPROEIER2 ON

        if (command == '3'){ //================== Instructie 3 => SPROEIER2 AUTO
          tuinWater2prog = 3;           //0=unknown, 1=off, 2=on, 3=auto, set ON
          EEPROM.write(6, 3);                         //Write 1 byte into EEPROM
          autoRelay();           //Switch sprinkler ON/OFF according to settings
        } //End of if (command == '3'){           Instructie 3 => SPROEIER2 AUTO

        if (command == '4'){ //======== Instructie 4 => SET SPROEITIJD SPROEIER2
          tuinWater2spray = value;          //Valude to switch from day to night
          EEPROM.write(7, tuinWater2spray);           //Write 1 byte into EEPROM
          autoRelay();           //Switch sprinkler ON/OFF according to settings
        } //End of if (command == '4')  Instructie 4 => SET SPROEITIJD SPROEIER2
      } //End of if (unit == '2') -------------- End of Command unit 2 => RELAY2


      if (panel == '3'){ //***************** Command panel 3 => RELAY3 SPROEIER3
        if (command == '1'){ //=================== Instructie 1 => SPROEIER3 OFF
          tuinWater3prog = 1;           //0=unknown, 1=off, 2=on, 3=auto, set ON
          EEPROM.write(8, 1);                         //Write 1 byte into EEPROM
          tuinRelay3 = 1;                              //Set SPROEIER3 OFF=1=UIT
          digitalWrite(Relay3Pin, 1);               //Switch SPROEIER3 OFF=1=UIT
        } //End of if (command == '1')             Instructie 1 => SPROEIER3 OFF

        if (command == '2'){ //==================== Instructie 2 => SPROEIER3 ON
          tuinWater3prog = 2;           //0=unknown, 1=off, 2=on, 3=auto, set ON
          EEPROM.write(8, 2);                         //Write 1 byte into EEPROM
          tuinRelay3 = 0;                               //Set SPROEIER3 ON=1=AAN
          digitalWrite(Relay3Pin, 0);                //Switch SPROEIER3 ON=1=AAN
        } //End of if (command == '2'){             Instructie 2 => SPROEIER3 ON

        if (command == '3'){ //================== Instructie 3 => SPROEIER3 AUTO
          tuinWater3prog = 3;           //0=unknown, 1=off, 2=on, 3=auto, set ON
          EEPROM.write(8, 3);                         //Write 1 byte into EEPROM
          autoRelay();           //Switch sprinkler ON/OFF according to settings
        } //End of if (command == '3'){           Instructie 3 => SPROEIER3 AUTO

        if (command == '4'){ //======== Instructie 4 => SET SPROEITIJD SPROEIER3
          tuinWater3spray = value;          //Valude to switch from day to night
          EEPROM.write(9, tuinWater3spray);           //Write 1 byte into EEPROM
          autoRelay();           //Switch sprinkler ON/OFF according to settings
        } //End of if (command == '4')  Instructie 4 => SET SPROEITIJD SPROEIER3
      } //End of if (unit == '3') -------------- End of Command unit 3 => RELAY3


      if (panel == '4'){ //***************** Command panel 4 => RELAY4 SPROEIER4
        if (command == '1'){ //=================== Instructie 1 => SPROEIER4 OFF
          tuinWater4prog = 1;           //0=unknown, 1=off, 2=on, 3=auto, set ON
          EEPROM.write(10, 1);                        //Write 1 byte into EEPROM
          tuinRelay4 = 1;                              //Set SPROEIER4 OFF=1=UIT
          digitalWrite(Relay4Pin, 1);               //Switch SPROEIER4 OFF=1=UIT
        } //End of if (command == '1')             Instructie 1 => SPROEIER4 OFF

        if (command == '2'){ //==================== Instructie 2 => SPROEIER4 ON
          tuinWater4prog = 2;           //0=unknown, 1=off, 2=on, 3=auto, set ON
          EEPROM.write(10, 2);                        //Write 1 byte into EEPROM
          tuinRelay4 = 0;                               //Set SPROEIER4 ON=1=AAN
          digitalWrite(Relay4Pin, 0);                //Switch SPROEIER4 ON=1=AAN
        } //End of if (command == '2'){             Instructie 2 => SPROEIER4 ON

        if (command == '3'){ //================== Instructie 3 => SPROEIER4 AUTO
          tuinWater4prog = 3;           //0=unknown, 1=off, 2=on, 3=auto, set ON
          EEPROM.write(10, 3);                        //Write 1 byte into EEPROM
          autoRelay();           //Switch sprinkler ON/OFF according to settings
        } //End of if (command == '3'){           Instructie 3 => SPROEIER4 AUTO

        if (command == '4'){ //======== Instructie 4 => SET SPROEITIJD SPROEIER4
          tuinWater4spray = value;          //Valude to switch from day to night
          EEPROM.write(11, tuinWater4spray);          //Write 1 byte into EEPROM
          autoRelay();           //Switch sprinkler ON/OFF according to settings
        } //End of if (command == '4')  Instructie 4 => SET SPROEITIJD SPROEIER4
      } //End of if (unit == '4') -------------- End of Command unit 4 => RELAY4
} //Exit checkCommand ----------------------------------------------------------






void autoRelay(void){ //*************** Switches ALL RELAY according to settings
    //Set minute counter to zero at daybreak and eveningfall and set autoTrigger

                        
  if (tuinLDR > LDRtreshold){                      //Dit betekent dat het is DAG
    if (tuinDayNight == LOW){         //Indien is Dag/Nacht nog set to LOW=NACHT
      tuinDayNight = HIGH;                     //Dan zet Dag/Nacht naar HIGH=DAG
      timerSprinkler = 0;        //Bovendien reset the sproeier coounter to zero
      if (tuinLDRprog==3){ //Indien het dag/nacht programma op automatisch staat
        tuinAutoTrigger = HIGH;  //HIGH=True=program, LOW=False=manual DAG/NACHT
      } //End of if (tuinLDRprog==3)
    } //End of if (tuinDayNight == LOW) 
    
  }else{                                         //Dit betekent dat het is NACHT
    if (tuinDayNight == HIGH){    //Indien is tuinDayNight still set to HIGH=DAG
      tuinDayNight = LOW;              //Dan zet het tuinDayNight naar LOW=NACHT
      timerSprinkler = 0;        //Bovendien reset the sproeier coounter to zero
      if (tuinLDRprog==3){ //Indien het dag/nacht programma op automatisch staat
        tuinAutoTrigger = HIGH;  //HIGH=True=program, LOW=False=manual DAG/NACHT
      } //End of if (tuinLDRprog==3)
    } //End of if (tuinDayNight == HIGH)
  } //End of if (tuinLDR > tuinLDRtreshold)


  if (tuinAutoTrigger == HIGH){     //Must be set to HIGH=Autoset om te sproeien
    if (timerSprinkler > tuinLDRdelay){      //If finished, see ifelse COOL DOWN
      endPeriod = tuinLDRdelay;         //End of cooldown for whichever sproeier
      doneSpraying = endPeriod + 1;                 //Reset the finished counter

      if (tuinWater1prog==3) {           //We kijken enkel indien SPROEIER1=AUTO
        startPeriod = tuinLDRdelay;//Start after cooldown for whichever sproeier
        endPeriod = startPeriod + tuinWater1spray; //Einde periode deze sproeier
        doneSpraying = endPeriod + 1;               //Reset the finished counter
        if (timerSprinkler < endPeriod) { //We zijn voor het einde van SPROEIER1
          if (timerSprinkler > startPeriod) {     //We zijn in periode SPROEIER1
            if (tuinRelay1==1) {  //Only if still switched off then SPROEIER1-ON
              tuinRelay1 = 0;                              //Set to SPROEIER1-ON
              digitalWrite(Relay1Pin, 0);                  //Switch SPROEIER1-ON
            } //End of if (tuinRelay1==1) If still switched on then SPROEIER1-ON
            if (tuinRelay2==0) {        //Only if switched on then OFF SPROEIER2
              tuinRelay2 = 1;                             //Set to off SPROEIER2
              digitalWrite(Relay2Pin, 1);                 //Switch off SPROEIER2
            } //End of if (tuinRelay2 == 0)    If switched on then OFF SPROEIER2
            if (tuinRelay3==0) {        //Only if switched on then OFF SPROEIER3
              tuinRelay3 = 1;                             //Set to off SPROEIER3
              digitalWrite(Relay3Pin, 1);                 //Switch off SPROEIER3
            } //End of if (tuinRelay3 == 0)    If switched on then OFF SPROEIER3
            if (tuinRelay4 == 0) {      //Only if switched on then OFF SPROEIER4
              tuinRelay4 = 1;                             //Set to off SPROEIER4
              digitalWrite(Relay4Pin, 1);                 //Switch off SPROEIER4
            } //End of if (tuinRelay4 == 0)    If switched on then OFF SPROEIER4
          } //End of (timerSprinkler > startPeriod) We zijn in periode SPROEIER1
        } //End of if (timerSprinkler < endPeriod)             Dit was SPROEIER1
      } //End of if (tuinWater1prog==3)       We kijken indien op AUTO SPROEIER1

      if (tuinWater2prog==3) {           //We kijken enkel indien SPROEIER2=AUTO
        startPeriod = endPeriod;   //Start voor volgende is eind vorige sproeier
        endPeriod = startPeriod + tuinWater2spray; //Einde periode deze sproeier
        doneSpraying = endPeriod + 1;               //Reset the finished counter
        if (timerSprinkler < endPeriod) { //We zoeken naar tijdvak van SPROEIER2
          if (timerSprinkler > startPeriod) {     //We zijn in periode SPROEIER2
            if (tuinRelay1 == 0) {//Only if still switched on then OFF SPROEIER1
              tuinRelay1 = 1;                             //Set to off SPROEIER1
              digitalWrite(Relay1Pin, 1);                 //Switch off SPROEIER1
            } //End of if (tuinRelay1 == 0)    If switched on then OFF SPROEIER1
            if (tuinRelay2==1) {  //Only if still switched off then SPROEIER2-ON
              tuinRelay2 = 0;                              //Set to SPROEIER2-ON
              digitalWrite(Relay2Pin, 0);                  //Switch SPROEIER2-ON
            } //End of if (tuinRelay2==1) If still switched on then SPROEIER2-ON
            if (tuinRelay3==0) {        //Only if switched on then OFF SPROEIER3
              tuinRelay3 = 1;                             //Set to off SPROEIER3
              digitalWrite(Relay3Pin, 1);                 //Switch off SPROEIER3
            } //End of if (tuinRelay3 == 0)    If switched on then OFF SPROEIER3
            if (tuinRelay4 == 0) {      //Only if switched on then OFF SPROEIER4
              tuinRelay4 = 1;                             //Set to off SPROEIER4
              digitalWrite(Relay4Pin, 1);                 //Switch off SPROEIER4
            } //End of if (tuinRelay4 == 0)    If switched on then OFF SPROEIER4
          } //End of (timerSprinkler > startPeriod) We zijn in periode SPROEIER2
        } //End of if (timerSprinkler < endPeriod)             Dit was SPROEIER2
      } //End of if (tuinWater2prog==3)       We kijken indien op AUTO SPROEIER2

      if (tuinWater3prog==3) {           //We kijken enkel indien SPROEIER3=AUTO
        startPeriod = endPeriod;  // Start voor volgende is eind vorige sproeier
        endPeriod = startPeriod + tuinWater3spray; //Einde periode deze sproeier
        doneSpraying = endPeriod + 1;               //Reset the finished counter
        if (timerSprinkler < endPeriod) {  //We zijn in de periode van SPROEIER3
          if (timerSprinkler > startPeriod) {     //We zijn in periode SPROEIER3
            if (tuinRelay1 == 0) {//Only if still switched on then OFF SPROEIER1
              tuinRelay1 = 1;                             //Set to off SPROEIER1
              digitalWrite(Relay1Pin, 1);                 //Switch off SPROEIER1
            } //End of if (tuinRelay1 == 0)    If switched on then OFF SPROEIER1
            if (tuinRelay2==0) {        //Only if switched on then OFF SPROEIER2
              tuinRelay2 = 1;                             //Set to off SPROEIER2
              digitalWrite(Relay2Pin, 1);                 //Switch off SPROEIER2
            } //End of if (tuinRelay2 == 0)    If switched on then OFF SPROEIER2
            if (tuinRelay3==1) {  //Only if still switched off then SPROEIER3-ON
              tuinRelay3 = 0;                              //Set to SPROEIER3-ON
              digitalWrite(Relay3Pin, 0);                  //Switch SPROEIER3-ON
            } //End of if (tuinRelay3==1) If still switched on then SPROEIER3-ON
            if (tuinRelay4 == 0) {      //Only if switched on then OFF SPROEIER4
              tuinRelay4 = 1;                             //Set to off SPROEIER4
              digitalWrite(Relay4Pin, 1);                 //Switch off SPROEIER4
            } //End of if (tuinRelay4 == 0)    If switched on then OFF SPROEIER4
          } //End of (timerSprinkler > startPeriod) We zijn in periode SPROEIER3
        } //End of if (timerSprinkler < endPeriod)             Dit was SPROEIER3
      } //End of if (tuinWater3prog==3)       We kijken indien op AUTO SPROEIER3

      if (tuinWater4prog==3) {           //We kijken enkel indien SPROEIER4=AUTO
        startPeriod = endPeriod;  // Start voor volgende is eind vorige sproeier
        endPeriod = startPeriod + tuinWater4spray; //Einde periode deze sproeier
        doneSpraying = endPeriod + 1;               //Reset the finished counter
        if (timerSprinkler < endPeriod) {  //We zijn in de periode van SPROEIER4
          if (timerSprinkler > startPeriod) {     //We zijn in periode SPROEIER4
            if (tuinRelay1 == 0) {//Only if still switched on then OFF SPROEIER1
              tuinRelay1 = 1;                             //Set to off SPROEIER1
              digitalWrite(Relay1Pin, 1);                 //Switch off SPROEIER1
            } //End of if (tuinRelay1 == 0)    If switched on then OFF SPROEIER1
            if (tuinRelay2==0) {        //Only if switched on then OFF SPROEIER2
              tuinRelay2 = 1;                             //Set to off SPROEIER2
              digitalWrite(Relay2Pin, 1);                 //Switch off SPROEIER2
            } //End of if (tuinRelay2 == 0)    If switched on then OFF SPROEIER2
            if (tuinRelay3==0) {        //Only if switched on then OFF SPROEIER3
              tuinRelay3 = 1;                             //Set to off SPROEIER3
              digitalWrite(Relay3Pin, 1);                 //Switch off SPROEIER3
            } //End of if (tuinRelay3 == 0)    If switched on then OFF SPROEIER3
            if (tuinRelay4==1) {  //Only if still switched off then SPROEIER4-ON
              tuinRelay4 = 0;                              //Set to SPROEIER4-ON
              digitalWrite(Relay4Pin, 0);                  //Switch SPROEIER4-ON
            } //End of if (tuinRelay4==1) If still switched on then SPROEIER4-ON
          } //End of (timerSprinkler > startPeriod) We zijn in periode SPROEIER4
        } //End of if (timerSprinkler < endPeriod)             Dit was SPROEIER4
      } //End of if (tuinWater4prog==3)       We kijken indien op AUTO SPROEIER4

      if (timerSprinkler > doneSpraying) { //Alles afgewerkt dus alles uit READY
        if (tuinRelay1 == 0) {    //Only if still switched on then OFF SPROEIER1
          tuinRelay1 = 1;                                 //Set to off SPROEIER1
          digitalWrite(Relay1Pin, 1);                     //Switch off SPROEIER1
        } //End of if (tuinRelay1 == 0)  If still switched on then OFF SPROEIER1
        if (tuinRelay2 == 0) {    //Only if still switched on then OFF SPROEIER2
          tuinRelay2 = 1;                                 //Set to off SPROEIER2
          digitalWrite(Relay2Pin, 1);                     //Switch off SPROEIER2
        } //End of if (tuinRelay2 == 0)  If still switched on then OFF SPROEIER2
        if (tuinRelay3 == 0) {    //Only if still switched on then OFF SPROEIER3
          tuinRelay3 = 1;                                 //Set to off SPROEIER3
          digitalWrite(Relay3Pin, 1);                     //Switch off SPROEIER3
        } //End of if (tuinRelay3 == 0)  If still switched on then OFF SPROEIER3
        if (tuinRelay4 == 0) {    //Only if still switched on then OFF SPROEIER4
          tuinRelay4 = 1;                                 //Set to off SPROEIER4
          digitalWrite(Relay4Pin, 1);                     //Switch off SPROEIER4
        } //End of if (tuinRelay4 == 0)  If still switched on then OFF SPROEIER4
      } //End of  if (timerSprinkler > doneSpraying)   Alles afgewerkt dus READY

    }else{                                                  //Still in COOL DOWN
        if (tuinRelay1 == 0) {    //Only if still switched on then OFF SPROEIER1
          tuinRelay1 = 1;                                 //Set to off SPROEIER1
          digitalWrite(Relay1Pin, 1);                     //Switch off SPROEIER1
        } //End of if (tuinRelay1 == 0)  If still switched on then OFF SPROEIER1
        if (tuinRelay2 == 0) {    //Only if still switched on then OFF SPROEIER2
          tuinRelay2 = 1;                                 //Set to off SPROEIER2
          digitalWrite(Relay2Pin, 1);                     //Switch off SPROEIER2
        } //End of if (tuinRelay2 == 0)  If still switched on then OFF SPROEIER2
        if (tuinRelay3 == 0) {    //Only if still switched on then OFF SPROEIER3
          tuinRelay3 = 1;                                 //Set to off SPROEIER3
          digitalWrite(Relay3Pin, 1);                     //Switch off SPROEIER3
        } //End of if (tuinRelay3 == 0)  If still switched on then OFF SPROEIER3
        if (tuinRelay4 == 0) {    //Only if still switched on then OFF SPROEIER4
          tuinRelay4 = 1;                                 //Set to off SPROEIER4
          digitalWrite(Relay4Pin, 1);                     //Switch off SPROEIER4
        } //End of if (tuinRelay4 == 0)  If still switched on then OFF SPROEIER4
      } //End of (timerSprinkler > tuinLDRdelay)              Finished COOL DOWN

  }else{ //Else of if (tuinAutoTrigger==HIGH) Must be set to HIGH om te sproeien
    if (tuinRelay1==0 && tuinWater1prog==3) {   //If still on then OFF SPROEIER1
      tuinRelay1 = 1;                                     //Set to off SPROEIER1
      digitalWrite(Relay1Pin, 1);                         //Switch off SPROEIER1
    } //End of if (tuinRelay1 == 0)      If still switched on then OFF SPROEIER1
    if (tuinRelay2==0 && tuinWater2prog==3) {   //If still on then OFF SPROEIER2
      tuinRelay2 = 1;                                     //Set to off SPROEIER2
      digitalWrite(Relay2Pin, 1);                         //Switch off SPROEIER2
    } //End of if (tuinRelay2 == 0)      If still switched on then OFF SPROEIER2
    if (tuinRelay3==0 && tuinWater3prog==3) {   //If still on then OFF SPROEIER3
      tuinRelay3 = 1;                                     //Set to off SPROEIER3
      digitalWrite(Relay3Pin, 1);                         //Switch off SPROEIER3
    } //End of if (tuinRelay3 == 0)      If still switched on then OFF SPROEIER3
    if (tuinRelay4==0 && tuinWater4prog==3) {   //If still on then OFF SPROEIER4
      tuinRelay4 = 1;                                     //Set to off SPROEIER4
      digitalWrite(Relay4Pin, 1);                         //Switch off SPROEIER4
    } //End of if (tuinRelay4 == 0)      If still switched on then OFF SPROEIER4
  } //End of if (tuinAutoTrigger==HIGH)       Must be set to HIGH om te sproeien
} //Exit autoRelay -------------------------------------------------------------






void DS1820_read(void) { //Reads the temperature from DS1820 in Celsius ********
  term1.reset();                              //Reset whatever still was running
  term1.select(addr1);                      //Set the parameters for the library
  term1.write(0x44);       //Start conversion, with parasite power on at the end
  delay(800);     //Maybe 750ms is enough, maybe not, takes a lot of time though
  present = term1.reset();              //We assume that the conversion is ready
  term1.select(addr1);                      //Set the parameters for the library
  term1.write(0xBE);                                          // Read Scratchpad
  for ( i = 0; i < 9; i++) {                                   //We need 9 bytes
    data[i] = term1.read();
  }
  int16_t raw = (data[1] << 8) | data[0];                      //Rotate the data
  tuinSoilTemp = (float)raw / 16.0;    //Untill they are in the correct position
} //Exit DS1820_read -----------------------------------------------------------



void DS1820_init(void) { //Determins the type of DS1820 thermometer1 ***********
  if (!term1.search(addr1)) {
    term1.reset_search();
    delay(250);
    return;
  }
  if (OneWire::crc8(addr1, 7) != addr1[7]) {
      return;
  }
  switch (addr1[0]) {         //The first ROM byte indicates which  tupe of chip
    case 0x10:
      type1_s = 1;
      break;
    case 0x28:
      type1_s = 0;
      break;
    case 0x22:
      type1_s = 0;
      break;
    default:
      return;
  } 
  term1.reset();
  term1.select(addr1);
  term1.write(0x44, 1);    //Start conversion, with parasite power on at the end
  delay(800);     //Maybe 750ms is enough, maybe not, takes a lot of time though
  present = term1.reset();
  term1.select(addr1);    
  term1.write(0xBE);                                           //Read Scratchpad
  for ( i = 0; i < 9; i++) {                                   //We need 9 bytes
    data[i] = term1.read();
  }

  int16_t raw = (data[1] << 8) | data[0];
  if (type1_s) {
    raw = raw << 3; // 9 bit resolution default
    if (data[7] == 0x10) {       // "count remain" gives full 12 bit resolution
      raw = (raw & 0xFFF0) + 12 - data[6];
    }
  } else {     //// default is 12 bit resolution, 750 ms conversion time
    byte cfg = (data[4] & 0x60);     
    // at lower res, the low bits are undefined, so let's zero them
    if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
  }
  tuinSoilTemp = (float)raw / 16.0;
} //Exit DS1820_init -----------------------------------------------------------





void EEPROMonBoot() { //Everytime time on boot use, write values into EEPROM ***
  EEPROM.write(  1,  3); //tuinLDR DAG/NACHT program 1=dag 2=nacht 3=auto RELAY0
  EEPROM.write(  4,  1);//tuinWater1prog WATER1 program 1=off 2=on 3=auto RELAY1
  EEPROM.write(  6,  1);//tuinWater2prog WATER2 program 1=off 2=on 3=auto RELAY2
  EEPROM.write(  8,  1);//tuinWater3prog WATER3 program 1=off 2=on 3=auto RELAY3
  EEPROM.write( 10,  1);//tuinWater4prog WATER4 program 1=off 2=on 3=auto RELAY4
} //Exit EEPROMfirstTime -------------------------------------------------------





void EEPROMfirstTime() { //First time use, write values into EEPROM ************
  EEPROM.write(  1,  1); //tuinLDR DAG/NACHT program 1=dag 2=nacht 3=auto RELAY0
  EEPROM.write(  2, 11);    //tuinLDRtreshold *10 to switch DAY=0/NIGHT=1023 LDR
  EEPROM.write(  3, 30);                //Number of minutes delay after dark ALL
  EEPROM.write(  4,  1);//tuinWater1prog WATER1 program 1=off 2=on 3=auto RELAY1
  EEPROM.write(  5, 10);     //tuinWater1spray Number of minutes water on RELAY1
  EEPROM.write(  6,  1);//tuinWater2prog WATER2 program 1=off 2=on 3=auto RELAY2
  EEPROM.write(  7, 10);     //tuinWater2spray Number of minutes water on RELAY2
  EEPROM.write(  8,  1);//tuinWater3prog WATER3 program 1=off 2=on 3=auto RELAY3
  EEPROM.write(  9, 10);     //tuinWater3spray Number of minutes water on RELAY3
  EEPROM.write( 10,  1);//tuinWater4prog WATER4 program 1=off 2=on 3=auto RELAY4
  EEPROM.write( 11, 10);     //tuinWater4spray Number of minutes water on RELAY4
} //Exit EEPROMfirstTime -------------------------------------------------------





void show_LAN(){ //Shows DHCP settings of LAN **********************************
  ether.printIp("My IP: ", ether.myip);
  ether.printIp("Netmask: ", ether.netmask);
  ether.printIp("GW IP: ", ether.gwip);
  ether.printIp("DNS IP: ", ether.dnsip);
} //Exit show_LAN --------------------------------------------------------------




void test_RELAY(){ //Switches ON for 2 seconds all RELAY ***********************
  digitalWrite(Relay1Pin, LOW);                         //Switches ON the RELAY1
  delay (6000);                                             //Wait for 2 seconds
  digitalWrite(Relay1Pin, HIGH);                       //Switches OFF the RELAY1
  digitalWrite(Relay2Pin, LOW);                         //Switches ON the RELAY2
  delay (6000);                                             //Wait for 2 seconds
  digitalWrite(Relay2Pin, HIGH);                       //Switches OFF the RELAY2
  digitalWrite(Relay3Pin, LOW);                         //Switches ON the RELAY3
  delay (6000);                                             //Wait for 2 seconds
  digitalWrite(Relay3Pin, HIGH);                       //Switches OFF the RELAY3
  digitalWrite(Relay4Pin, LOW);                         //Switches ON the RELAY4
  delay (6000);                                             //Wait for 2 seconds
  digitalWrite(Relay4Pin, HIGH);                       //Switches OFF the RELAY4
} //End of test_Relay(){ Switches ON for 2 seconds the RELAY -------------------



void test_LEDs(void){ //PWM fade in and fade out for all 4 LEDs on board *******
  brillance = 0;                 //Brightness of any color, just to test PWM LED

  while (brillance<255){
    analogWrite(ledRedPin, brillance);        //Set LED to desired PWM value RED
    brillance++;
    delay (msWait);
  }
  while (brillance>0){
    analogWrite(ledRedPin, brillance);        //Set LED to desired PWM value RED
    brillance--;
    delay (msWait);
  }
  analogWrite(ledRedPin, 0);            //Set LED to desired PWM value = off RED

  while (brillance<255){
    analogWrite(ledGrePin, brillance);      //Set LED to desired PWM value GREEN
    brillance++;
    delay (msWait);
  }
  while (brillance>0){
    analogWrite(ledGrePin, brillance);      //Set LED to desired PWM value GREEN
    brillance--;
    delay (msWait);
  }
  analogWrite(ledGrePin, 0);          //Set LED to desired PWM value = off GREEN

  while (brillance<255){
    analogWrite(ledBluPin, brillance);       //Set LED to desired PWM value BLUE
    brillance++;
    delay (msWait);
  }
  while (brillance>0){
    analogWrite(ledBluPin, brillance);       //Set LED to desired PWM value BLUE
    brillance--;
    delay (msWait);
  }
  analogWrite(ledBluPin, 0);           //Set LED to desired PWM value = off BLUE

  while (brillance<255){
    analogWrite(LED_BUILTIN, brillance);  //Set to desired PWM value LED_BUILTIN
    brillance++;
    delay (msWait);
  }
  while (brillance>0){
    analogWrite(LED_BUILTIN, brillance);  //Set to desired PWM value LED_BUILTIN
    brillance--;
    delay (msWait);
  }
  analogWrite(LED_BUILTIN, 0);  //Set LED to desired PWM value = off LED_BUILTIN
} //Exit test_LEDs -------------------------------------------------------------



void beep(uint8_t ms) {      //Create a beep (x5ms) with KY-012 active BUZZER **
  digitalWrite(buzActPin,HIGH);                                 //Turn on BUZZER
  while (ms > 0){                     //Timer of the duration of the beep BUZZER
    delay(5);                                         //Wait milliseconds BUZZER
    ms--;                              //Countdown untill we reached zero BUZZER
  }                 //Timer of the duration has been counted down to zero BUZZER
  digitalWrite(buzActPin,LOW);                  //Turn annoying sound off BUZZER
} //Exit beep ------------------------------------------------------------------



void toggleBlueLed(void){ //Toggles ON or OFF the blue LED *********************
  if (ledBlueVal > 0){
    ledBlueVal = 0;
    digitalWrite(ledBluPin, 0);               //Set according to switch blue LED
  }else{
    ledBlueVal = 20;                                              //Toggle value
    analogWrite(ledBluPin, ledBlueVal);       //Set according to switch blue LED
  }
} //Exit toggle_ledBin ---------------------------------------------------------



void toggle_ledOnBoard(void){ //Toggles the LED_BUILTIN on-board LED on or off *
  ledOnBoardVal = !ledOnBoardVal;                                 //Toggle value
  digitalWrite(LED_BUILTIN, ledOnBoardVal);     //Set Arduino boards onboard LED
} //Exit toggle_ledBin ---------------------------------------------------------




void disable_jtag(void) { //Disable jtag to free port C, enabled by default ****
#if defined(JTD)                           //Not all AVR controller include jtag
  MCUCR |= ( 1 << JTD );                                //Write twice to disable
  MCUCR |= ( 1 << JTD );                                       //So stutter once
#endif                                            //End of conditional compiling
} //Exit jtag_disable ----------------------------------------------------------




////////////////////////////////////////////////////////////////////////////////
// PIN ALLOCATIONS TABLE ARDUINO UNO                                          //
// Board -Atmel- PIN - IDE - Function          - Connection               ALT //
//                                                                            //
// CONNECTIONS RAILS TOP LEFT: DIGITAL PWM<~> ******************************* //
// SCL   -  28 - PC5 -19/A5- ADC5/SCL/PCINT13  - DS1307 Clock             TWI //
// SDA   -  27 - PC4 -18/A4- ADC4/SDA/PCINT12  - DS1307 Clock             TWI //
// AREF  -  21 - REF -     - AREF              -                              //
// GND   -  22 - GND -     - GND               -                              //
// 13    -  19 - PB5 -  13 - SCK/PCINT5        - LAN SPI SCK  LED_BUILTIN/SPI //
// 12    -  18 - PB4 -  12 - MISO/PCINT4       - LAN SPI MISO             SPI //
// ~11   -  17 - PB3 -  11 - MOSI/OC2A/PCINT3  - LAN SPI MOSI             PWM //
// ~10   -  16 - PB2 -  10 - SS/OC1B/PCINT2    - LSN SPI SS / CS          PWM //
// ~9    -  15 - PB1 -   9 - OC1A/PCINT1       - Relay2                   PWM //
// 8     -  14 - PB0 -   8 - PCINT0/CLK0/ICP1  - LAN CLK                  DIO //
//                                                                            //
// CONNECTIONS RAILS TOP RIGHT: DIGITAL PWM<~> ****************************** //
// 7     -  13 - PD7 -   7 - PCINT23/AIN1      - Relay1                   DIO //
// ~6    -  12 - PD6 -   6 - PCINT22/OCA0/AIN0 - ledBluPin                PWM //
// ~5    -  11 - PD5 -   5 - PCINT21/OC0B/T1   - ledGrePin                PWM //
//  4    -   6 - PD4 -   4 - PCINT20/XCK/T0    - buzActPin                DIO //
// ~3    -   5 - PD3 -   4 - PCINT19/XCK/T0    - ledRedPin                PWM //
//  2    -   4 - PD2 -   2 - PCINT18/INT0      -                          INT //
// TX->1 -   3 - PD1 -   1 - PCINT17/TXD       - Serial monitor           TXD //
// RX<-0 -   2 - PD0 -   0 - PCINT16/RCD       - Serial monitor           RCD //
//                                                                            //
// CONNECTIONS RAILS BOTTOM LEFT: POWER ************************************* //
// 5V    -   7 - VCC -      - VCC              - Output to breadboard     VCC //
// RES   -   1 - RES -      - PCINT14/RESET    -                          RES //
// 3.3V  -     -     -     -                   -                              //
// 5V    -     -     -     -                   -                              //
// GND   -     -     -     -                   -                              //
// GND   -     -     -     -                   - Buck                         //
// Vin   -     -     -     -                   - Buck 12Vdc --> 7Vdc          //
//                                                                            //
// CONNECTIONS RAILS BOTTOM RIGHT: ANALOG IN ******************************** //
// A0    -  23 - PC0 -A0/14- ADC0/PCINT8       - DS18B20                  ADC //
// A1    -  24 - PC1 -A1/15- ADC1/PCINT9       - ldrPin                   ADC //
// A2    -  25 - PC2 -A2/16- ADC2/PCINT10      - Relay4                   ADC //
// A3    -  26 - PC3 -A3/17- ADC3/PCINT12      - Relay3                   ADC //
// A4    -  27 - PC4 -A4/18- ADC4/SDA/PCINT12  - DS1307 Clock             TWI //
// A5    -  28 - PC5 -A5/19- ADC5/SCL/PCINT13  - DS1307 Clock             TWI //
////////////////////////////////////////////////////////////////////////////////
// EEPROM MEMORY MAP:                                                         //
// Start End  Number Description                                              //
// 0000  0000      1   Never use this memory location to be AVR compatible    //
// 0001  0001      1   tuinLDRtreshold *10 to switch DAY=0/NIGHT=1023     LDR //
// 0002  0002      1   Number of minutes tuinWaterDelay after dark        ALL //
// 0003  0003      1 WATER1 tuinWater1prog program 1=off 2=on 3=auto   RELAY1 //
// 0004  0004      1   Number of minutes tuinWater1spray water on      RELAY1 //
// 0005  0005      1 WATER2 tuinWater2prog program 1=off 2=on 3=auto   RELAY2 //
// 0006  0006      1   Number of minutes tuinWater2spray water on      RELAY2 //
// 0007  0007      1 WATER3 tuinWater3prog program 1=off 2=on 3=auto   RELAY3 //
// 0008  0008      1   Number of minutes tuinWater3spray water on      RELAY3 //
// 0009  0009      1 WATER4 tuinWater4Pprog program 1=off 2=on 3=auto  RELAY4 //
// 0010  0010      1   Number of minutes tuinWater4spray water on      RELAY4 //
////////////////////////////////////////////////////////////////////////////////
//345678911234567892123456789312345678941234567895123456789612345678971234567898
////////////////////////////////////////////////////////////////////////////////
// FUSES (can always be altered by using the STK500)                          //
// On-Chip Debug Enabled: off                            (OCDEN=0)            //
// JTAG Interface Enabled: off                           (JTAGEN=0)           //
// Preserve EEPROM mem through the Chip Erase cycle: On  (EESAVE = 0)         //
// Boot Flash section = 2048 words, Boot startaddr=$3800 (BOOTSZ=00)          //
// Boot Reset vector Enabled, default address=$0000      (BOOTSTR=0)          //
// CKOPT fuse (operation dependent of CKSEL fuses        (CKOPT=0)            //
// Brown-out detection level at VCC=2,7V;                (BODLEVEL=0)         //
// Ext. Cr/Res High Freq.; Start-up time: 16K CK + 64 ms (CKSEL=1111 SUT=11)  //
//                                                                            //
// LOCKBITS (are dangerous to change, since they cannot be reset)             //
// Mode 1: No memory lock features enabled                                    //
// Application Protect Mode 1: No lock on SPM and LPM in Application Section  //
// Boot Loader Protect Mode 1: No lock on SPM and LPM in Boot Loader Section  //
////////////////////////////////////////////////////////////////////////////////