////////////////////////////////////////////////////////////////////////////////
// Name:       Couveuse2_Arduino_Uno_02                                       //
//             Versie 2 voegt WiFi toe                                        //
// Platform:   Arduino UNO R3                                                 //
// Created by: HARB rboek2@gmail.com Januar 2020 GPL copyrights               //
// http://robotigs.com/robotigs/includes/bots_header.php?idbot=22             //
// This program is made to communicate via RS232. Buffers are C-style.        //
// Improvement of the response speed over version 01 by using a buffer        //
// See https://www.mcgurrin.info/robots/127/ on printing data types           //
////////////////////////////////////////////////////////////////////////////////



// SET PRECOMPILER OPTIONS *****************************************************
  //Initialse conditional compiling, uncomment to include, comment to exclude --
  // Do comment for runtime versions
  //#define RS232                 //Uncomment to include Serial Monitor sections


  //Define the needed header files for the precompiler, no charge if not used --
  #include <RTClib.h>        //Manipulates clock via I2C needs Wire.h lib DS1307
             // http://robotigs.nl/robotigs/includes/parts_header.php?idpart=289
  #include <Wire.h>     //Needed ao by RTClib: Two Wire Interface lib TWI DS1307
              // http://robotigs.nl/robotigs/includes/parts_header.php?idpart=31
  #include <OneWire.h>    //Library can be installed through Arduino IDE DS18B20
             // http://robotigs.nl/robotigs/includes/parts_header.php?idpart=180
  #include <EEPROM.h>               //Needed to read or write settings in EEPROM
             // http://robotigs.nl/robotigs/includes/parts_header.php?idpart=312
  #include <WiFiEsp.h>                           //Library for ESP01 Wifi module
              //http://robotigs.nl/robotigs/includes/parts_header.php?idpart=238
  #include <SoftwareSerial.h>          //Library to communicate with Wifi module
               //http://robotigs.nl/robotigs/includes/parts_header.php?idpart=43

  //Define PINS ----------------------------------------------------------------
  #define heaterPin     2                  //Pin connects VERWARMINGSMAT RELAIS1
  #define ledBluPin     3        //3 Colour LED, which PWM pin connects BLUE LED
  #define lightPin      4                //Pin connects GROEIVERLICHTING RELAIS2
  #define ledGrePin     5       //3 Colour LED, which PWM pin connects GREEN LED
  #define ledRedPin     6         //3 Colour LED, which PWM pin connects RED LED
  #define SDssPin      10                   //SPI Chip select pin at the SD CARD
  OneWire term1(8);           //Connects to pin 8, but may be any DIO pin DS1820

  //Define EEPROM variables ----------------------------------------------------
  int     progHeater = EEPROM.read(1);     //VERWARMING 1=off 2=auto 3=on RELAY1
  int     tempOn     = EEPROM.read(2);       //Temp Celcius verwarming ON RELAY1
  int     tempOff    = EEPROM.read(3);      //Temp Celcius verwarming OFF RELAY1
  int     progLed    = EEPROM.read(4);    //VERLICHTING 1=off 2=auto 3=on RELAY2
  int     hoursLed   = EEPROM.read(5);       //Burning hours around 13:00 RELAY2
  int     ledRedBril = EEPROM.read(6);            //Current brillance of RED LED
  int     ledGreBril = EEPROM.read(7);          //Current brillance of GREEN LED
  int     ledBluBril = EEPROM.read(8);           //Current brillance of BLUE LED
  int     freqMeasSec= EEPROM.read(9);   //Measurement sensors every seconds SYS
  int     versionMaj = EEPROM.read(10);                       //Versie Major SYS
  int     versionMin = EEPROM.read(11);                       //Versie Minor SYS
  int     versionRev = EEPROM.read(12);                    //Versie Revision SYS
  int     serialNum  = EEPROM.read(13);                      //Serial Number SYS
  char    ssid[]         = "Ranonkel9";               //Network SSID (name) WIFI
  char    pass[]         = "Kat14_-5";                   //Network password WIFI


  //Define DATABASE VARIABLES --------------------------------------------------
  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
  float   tempDS18B20;                     //Soil temperature in Celsius DS18B20
  int     ledRedStatus   =     0;           //0-255 current status for pc of LED
  int     ledGreStatus   =     0;           //0-255 current status for pc of LED
  int     ledBluStatus   =     0;           //0-255 current status for pc of LED
  bool    heaterStatus   =  HIGH;   //Status HIGH=off, LOW=on VERWARMING RELAIS1
  bool    lightStatus    =  HIGH;      //Status 1=off,  0=on VERLICHTING RELAIS2

  //Define variables -----------------------------------------------------------
  int    ledOnBoardVal  =   LOW; //You choose HIGH-on or LOW-off for LED_BUILTIN
  int    brillance      =     0;   //Used in testleds to count down TEST ALL LED
  word   msWait         =    20;   //Used in testleds to count down TEST ALL LED
  int    startHour;                                 //Switch ON time VERLICHTING
  int    finishHour;                               //Switch OFF time VERLICHTING
  word   readCounter    =     0;  //Read sensors if counted down to zero SENSORS
  word   readTimer      =    16;  //Fill readCounter after reaching zero SENSORS
  word   dataCounter    =     3;     //Eerst 3 rondjes wachten voor stabilisatie
  word   dataTimer      =    60;      //60 = Ong 5 minuten per reading save data
  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
  byte   commandByte    =  0;                   //Create receive string INTERNET
  String receiveStr     = "";                   //Create receive string INTERNET
  int    byteReceived   =     0;    //Individual bytes received by program RS232
  String currentData    =    "";//Export through RS232 or show on SERIAL MONITOR
  String filename       = "couveus2.dat";                   //File on the SDcard
  int    status         = WL_IDLE_STATUS;             //Status of the ESP01 WIFI
  static String html    = "";                //Creating response string INTERNET
  int    panel          =  1;                                 //Panel to PERFORM
  char   commando       =  0;                               //Command to PERFORM
  int    value          =  6;           //Set a temperature or hours for PERFORM
  String tmp2           = "";                      //Can be used anywhere DS1307
  int    tmp1;                                            //Can be used ANYWHERE
  String tmp            = "";                             //Can be used anywhere
  String tempo          = "";                             //Can be used anywhere
  String tmpStr         = " ";                            //Can be used anywhere

  //Initialize OBJECTS ---------------------------------------------------------
  SoftwareSerial mySerial(9, 7);                                        //RX, TX
  DS1307 rtc;                         //Initialize Real Time Clock object DS1307
  WiFiEspServer server(80);                           //Start the webserver WIFI
//END OF PRECOMPILER OPTIONS ---------------------------------------------------

void setup() { //Setup runs once ***********************************************
  disable_jtag();       //Disable jtag to free port C, enabled by default SYSTEM
  Serial.begin(57600);        //Nothing more needed for the Serial Monitor RS232
  mySerial.begin(57600);         //Nothing more needed to connect to module WIFI
  pinMode(LED_BUILTIN, OUTPUT);  //Arduino boards contain an onboard LED_BUILTIN
  pinMode(heaterPin, OUTPUT);              //Pin connects VERWARMINGSMAT RELAIS1
  pinMode(lightPin, OUTPUT);             //Pin connects GROEIVERLICHTING RELAIS2
  digitalWrite(heaterPin, heaterStatus);               //Switches OFF the RELAY1
  digitalWrite(lightPin, lightStatus);                 //Switches OFF the RELAY2

  //Start objects --------------------------------------------------------------
  initializeWiFI();                   //Initializes and connects to network WIFI
  //EEPROMfirstTime();                    //First time use, set values in EEPROM
  initVerlichting();              //Calculate start and finisch time verlichting
  DS1820_init();      //Determins the type of DS1820 and reads properties DS1820
  Wire.begin();                 //Start the Two Wire Interface object I2C DS1307
  rtc.begin();    //Initialize Wire.begin first. Start the object running DS1307
  //rtc.adjust(DateTime(__DATE__, __TIME__));      //Set to time compiled DS1307

  //Test hardware and software -------------------------------------------------
  test_LEDs();       //PWM fade in and fade out for 3 colorLEDs on board ALL LED
  //test_RELAY();                          //Switches ON for 2 seconds all RELAY
  //Serial.println("Start loop");                       //Show on SERIAL MONITOR
} //End of setup ---------------------------------------------------------------





void loop() { //KEEP ON RUNNING THIS LOOP FOREVER ******************************
  readClock();          //Read timestamp and write results into variables DS1307
  readSensors();         //Read most sensors but at timed intervals only SENSORS
  checkWifi();      //Check if any request available and if so then respond WIFI
}//End of void loop() ------------------------ KEEP ON RUNNING THIS LOOP FOREVER







void readClock(){ //Read timestamp and write 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
} //Exit readTime --------------------------------------------------------------




void readSensors() { //Read several sensors at timed intervals only ************
  if (readCounter == 0){       //Only perform measurements if counted down TIMER
    analogWrite(ledGrePin, ledRedBril);     //Green HIGH=on, LOW=off activityLED
    DS1820_read();               //Reads the temperature in Celsius from DS18B20
    readCounter = readTimer * freqMeasSec;             //RESET the counter TIMER
    setRelay1();                   //VERWARMING switch, calculate and set RELAY1
    setRelay2();                  //VERLICHTING switch, calculate and set RELAY2
    Serial.println(html);              //Broadcast the message to be shown RS232
    if (dataCounter == 0) {
      dataCounter = dataTimer;
      //writeSDdata();
    }else{
      dataCounter--;
    }
    refreshAnswer();                  //Replace the old answer by a new one WIFI
    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 sendHttpResponse(WiFiEspClient client) { //Sends measurements WIFI ********
  client.println("HTTP/1.1 200 OK");          //Start answer to the request WIFI
  client.println("Connection: close");       //Close after html is finished WIFI
  client.println("Content-Type: text/html");      //Needed to be compatible WIFI
  client.println(" /n \n");                     //Needed to end the headers WIFI
  client.println(html);      //Broadcast the message to be shown in browser WIFI
} //Exit sendHttpResponse ------------------------------------------------------






void checkWifi(){   //Check if any request available and if so then respond WIFI
  WiFiEspClient client = server.available();  //Listen for incoming clients WIFI
  if (client) {                               //If you get a client then do WIFI
    digitalWrite(ledBluPin, HIGH);           //Blue HIGH=on, LOW=off activityLED
    receiveStr = client.readStringUntil('\n');           //Read until first CRLF
    client.flush();              //Empty the buffer with the rest of the request
    performCommand();                  //Do as user orders to do for all streams
    sendHttpResponse(client);              //Meaning the end of the HTTP request
    client.stop();                              //Close the Wifi connection WIFI
    digitalWrite(ledBluPin, LOW);            //Blue HIGH=on, LOW=off activityLED
  } //End of if (client)                      //If you get a client then do WIFI
} //Exit checkWifi -------------------------------------------------------------



void initializeWiFI(){ //Initializes and connects to network *******************
  WiFi.init(&mySerial);                           //Initialize ESP01 module WIFI
  if (WiFi.status() == WL_NO_SHIELD) {   //Check the presence of the module WIFI
    Serial.println("WiFi module not present");    //Show error to the user RS232
    while (true);                  //Don't continue by looping here forever WIFI
  } //End of if (WiFi.status() == WL_NO_SHIELD) {        Check the presence WIFI
  while (status != WL_CONNECTED) {     //Attempt connecting to WiFi network WIFI
    Serial.print("Attempting to connect to WPA SSID: "); //Show connecting RS232
    Serial.println(ssid);            //Show fixed network name to the user RS232
    status = WiFi.begin(ssid, pass);             //Connected to WPA/WPA2 network
  } //End of while (status != WL_CONNECTED)  Keep on trying until connected WIFI
  server.begin();                         //Start the web server on port 80 WIFI
} //End of initializeWiFI(){ Initializes and connects to network ---------------



void refreshAnswer(void) { //Replace the old answer by a new one WIFI **********
  html =  String(jaar) + " ";                                        //Timestamp
  html += String(maand) + " ";                                       //Timestamp
  html += String(dag) + " ";                                         //Timestamp
  html += String(uur) + " ";                                         //Timestamp
  html += String(minuut) + " ";                                      //Timestamp
  html += String(seconde) + " ";                                     //Timestamp
  html += String(tempDS18B20) + " ";            //Temperature in Celcius DS18B20
  html += String(heaterStatus) + " "; //Status HIGH=off LOW=on VERWARMING RELAY1
  html += String(progHeater) + " ";        //VERWARMING 1=off 2=auto 3=on RELAY1
  html += String(tempOn) + " ";       //Temperature Celcius verwarming ON RELAY1
  html += String(tempOff) + " ";     //Temperature Celcius verwarming OFF RELAY1
  html += String(lightStatus) + " "; //Status HIGH=off LOW=on VERLICHTING RELAY2
  html += String(progLed) + " ";          //VERLICHTING 1=off 2=aut 3=off RELAY2
  html += String(hoursLed) + " "; //Burning hrs around 13:00h VERLICHTING RELAY2
  html += String(freqMeasSec);           //Measurement sensors every seconds SYS
} //Exit refreshAnswer ---------------------------------------------------------




void performCommand() { //Check if any command has been raised *****************
  tmpStr = receiveStr.substring(7, 8);                   //Extract command 01-99
  panel = tmpStr.toInt();               //Translate the function to a executable
  Serial.println(panel);                    //Showing we handeld a request RS232
  tmpStr = receiveStr.substring(9, 10);                  //Extract command 01-99
  commando = tmpStr.toInt();            //Translate the function to a executable
  tmpStr = receiveStr.substring(11,15);                   //Extract value 01-255
  value = tmpStr.toInt();         //Translate into a temerature or hours setting

  Serial.print("-");                        //Showing we handeld a request RS232
  Serial.print(receiveStr);                 //Showing we handeld a request RS232
  Serial.print("-");                        //Showing we handeld a request RS232
  Serial.print(panel);                      //Showing we handeld a request RS232
  Serial.print("-");                        //Showing we handeld a request RS232
  Serial.print(commando + 48);              //Showing we handeld a request RS232
  Serial.println("-");                      //Showing we handeld a request RS232

  switch (panel) {      //Go to the according panel /flora/includes/florabot.php

    case 1: //==================================== Command panel 1 = DS1307 KLOK
      switch (commando) {                        //Go to the according procedure

        case 1:                            //Adjust clock with given time DS1307
          tmpStr = receiveStr.substring(11, 15);             //Extract 0000-9999
          jaar = tmpStr.toInt();                //Translate the data into a year
          tmpStr = receiveStr.substring(16, 18);                 //Extract 01-12
          maand = tmpStr.toInt();              //Translate the data into a month
          tmpStr = receiveStr.substring(19, 21);                 //Extract 01-31
          dag = tmpStr.toInt();                  //Translate the data into a day
          tmpStr = receiveStr.substring(22, 24);                 //Extract 00-23
          uur = tmpStr.toInt();                 //Translate the data into a hour
          tmpStr = receiveStr.substring(25, 27);                 //Extract 00-59
          minuut = tmpStr.toInt();            //Translate the data into a minute
          tmpStr = receiveStr.substring(28, 30);                 //Extract 00-59
          seconde = tmpStr.toInt();          //Translate the data into a seconds
          Serial.println("YES");            //Showing we handeld a request RS232
          Serial.println(uur);                           //Showing data at RS232
          Serial.println(minuut);                        //Showing data at RS232
          Serial.println(seconde);                       //Showing data at RS232
          rtc.adjust(DateTime(jaar, maand, dag, uur, minuut, seconde)); //DS1307
          setRelay2();            //VERLICHTING switch, calculate and set RELAY2
          break;                   //case 1: Adjust clock with given time DS1307
      } //End of switch (commando)                 Go to the according procedure
    break;                                       //Command panel 1 = DS1307 KLOK

    case 2: //===================================== Command panel 2 = VERWARMING
      switch (commando) {                        //Go to the according procedure
        
        case 1:                                //Set program 1 => VERWARMING OFF
          progHeater = 1;                       //0=unknown, 1=off, 2=on, 3=auto
          EEPROM.write(1, 1);                         //Write 1 byte into eeprom
          setRelay1();                                //Calculate and set relay1
        break;
        case 2:                               //Set program 2 => VERWARMING AUTO
          progHeater = 2;                       //0=unknown, 1=off, 2=on, 3=auto
          EEPROM.write(1, 2);                         //Write 1 byte into eeprom
          setRelay1();                                //Calculate and set relay1
        break;
        case 3:                                 //Set program 3 => VERWARMING ON
          progHeater = 3;                       //0=unknown, 1=off, 2=on, 3=auto
          EEPROM.write(1, 3);                         //Write 1 byte into eeprom
          setRelay1();                                //Calculate and set relay1
        break; 

        case 4:                           //Set aanschakeltemperatuur VERWARMING
          tempOn = value;                                       //Set to reading
          EEPROM.write(2, tempOn);                    //Write 1 byte into eeprom
          setRelay1();                                //Calculate and set relay1
        break;

        case 5:                           //Set uitschakeltemperatuur VERWARMING
          tempOff = value;                                      //Set to reading
          EEPROM.write(3, tempOff);                   //Write 1 byte into eeprom
          setRelay1();                                //Calculate and set relay1
        break;
      } //End of switch (commando)
    break;                                        //Command panel 2 = VERWARMING


    case 3: //==================================== Command panel 3 = VERLICHTING
      switch (commando) {                        //Go to the according procedure
        
        case 1:                               //Set program 1 => VERLICHTING OFF
          progLed = 1;                          //0=unknown, 1=off, 2=on, 3=auto
          EEPROM.write(4, 1);                         //Write 1 byte into eeprom
          setRelay2();                                //Calculate and set relay2
        break;
        case 2:                              //Set program 2 => VERLICHTING AUTO
          progLed = 2;                          //0=unknown, 1=off, 2=on, 3=auto
          EEPROM.write(4, 2);                         //Write 1 byte into eeprom
          setRelay2();                                //Calculate and set relay2
        break;
        case 3:                                //Set program 3 => VERLICHTING ON
          progLed = 3;                          //0=unknown, 1=off, 2=on, 3=auto
          EEPROM.write(4, 3);                         //Write 1 byte into eeprom
          setRelay2();                                //Calculate and set relay2
        break; 

        case 4:                          //Set aanschakeltemperatuur VERLICHTING
          hoursLed = value;                                     //Set to reading
          EEPROM.write(5, hoursLed);                  //Write 1 byte into eeprom
          initVerlichting();      //Calculate start and finisch time verlichting
          setRelay2();                                //Calculate and set relay2
        break;
      } //End of switch (commando)

   break;                                        //Command panel 3 = VERLICHTING
  } //End of switch (panel)     the according panel /flora/includes/florabot.php

  refreshAnswer();                    //Replace the old answer by a new one WIFI
} //Exit performCommand --------------------------------------------------------




void setRelay1(){ //HEATER switch, calculate and set RELAY1 ********************
  switch (progHeater) {               //HEATER program: 1=off 2=auto 3=on RELAY1
    case 1:                      //Program = 1 = Set program  VERWARMINGSMAT OFF
      heaterStatus = HIGH;      //Status HIGH=off, LOW=on VERWARMINGSMAT RELAIS1
    break;                //End of Program = 1 = Set program  VERWARMINGSMAT OFF

    case 2:                      //Program = 3 = Set program VERWARMINGSMAT AUTO
      if (tempDS18B20 < tempOn){               //If treshold measurement TURN ON
        heaterStatus = LOW;         //Status HIGH=off or LOW=on HEATER ON RELAY1
      } //End of                                 If treshold measurement TURN ON
      if (tempDS18B20 > tempOff){             //If treshold measurement TURN OFF
        heaterStatus = HIGH;        //Status HIGH=off or LOW=on HEATER ON RELAY1
      } //End of                                If treshold measurement TURN OFF
    break;                   //End of Program = 2 = Set program COIL HEATER AUTO

    case 3:                       //Program = 3 = Set program  VERWARMINGSMAT ON
      heaterStatus = LOW;     //Status HIGH=off or LOW=on  VERWARMINGSMAT RELAY3
    break;                 //End of Program = 3 = Set program  VERWARMINGSMAT ON
  }                                                       //End of switch HEATER
  digitalWrite(heaterPin, heaterStatus);                       //Switches RELAY1
} //Exit setRelay1 -------------------------------------------------------------



void setRelay2(){ //VERLICHTING switch, calculate and set RELAY2 ***************
  switch (progLed) {             //VERLICHTING program: 1=off 2=auto 3=on RELAY2
    case 1:                     //Program = 1 = Set program GROEIVERLICHTING OFF
      lightStatus = HIGH;    //Status HIGH=off or LOW=on GROEIVERLICHTING RELAY4
    break; //Case 1        End of Program = 1 = Set program GROEIVERLICHTING OFF

    case 2:                         //Program = 2 = Set program VERLICHTING AUTO
      if (uur < startHour){                         //Too early, VERLICHTING OFF
         lightStatus = HIGH;      //Switch OFF , HIGH=off LOW=on VERLICHTING OFF
      } //End of if (currenthour < starthours){     //Too early, VERLICHTING OFF
      if (uur > finishHour -1){                      //Too late, VERLICHTING OFF
         lightStatus = HIGH;      //Switch OFF , HIGH=off LOW=on VERLICHTING OFF
      } //End of if (currenthour > finishhours)        Too late, VERLICHTING OFF
      if (uur > (startHour-1) && uur < (finishHour)){                       //ON
         lightStatus = LOW;         //Switch ON , HIGH=off LOW=on VERLICHTING ON
      } //End of  if (currenthour > (starthours-1) && currenthour <(finishhours)
    break; //Case 2            End of Program = 2 = Set program VERLICHTING AUTO

    case 3:                           //Program = 3 = Set program VERLICHTING ON
      lightStatus = LOW;          //Status HIGH=off or LOW=on VERLICHTING RELAY2
    break; //Case 3              End of Program = 3 = Set program VERLICHTING ON

  } //End of switch (progLed)      VERLICHTING program: 1=off 2=auto 3=on RELAY2
  digitalWrite(lightPin, lightStatus);               //Switch VERLICHTING RELAY2
} //Exit setRelay2 -------------------------------------------------------------






void initVerlichting() { //Calculate start and finisch time VERLICHTING ********
  startHour  = 13 - (hoursLed / 2);       //Calculate switch ON time VERLICHTING
  finishHour = 13 + (hoursLed / 2);      //Calculate switch OFF time VERLICHTING
} //Exit initVerlichting -------------------------------------------------------






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();                                  //Read byte by byte
  }                                                       //End of reading bytes
  int16_t raw = (data[1] << 8) | data[0];                      //Rotate the data
  tempDS18B20 = (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 is an objest created by ONEWIRE
    term1.reset_search();                  //So if the variables are still empty
    delay(250);          //The variables must be filled and that costs some time
    return;                               //Are you sure any DS1820 is connected
  }                                           //End of if (!term1.search(addr1))
  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
  }
  tempDS18B20 = (float)raw / 16.0;
} //Exit DS1820_init -----------------------------------------------------------



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<10){
    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<10){
    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<10){
    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
} //Exit test_LEDs -------------------------------------------------------------




void test_RELAY(){ //Switches ON for 2 seconds all RELAY ***********************
  digitalWrite(heaterPin, LOW);                         //Switches ON the RELAY1
  delay (2000);                                             //Wait for 2 seconds
  digitalWrite(heaterPin, HIGH);                       //Switches OFF the RELAY1
  digitalWrite(lightPin, LOW);                          //Switches ON the RELAY2
  delay (2000);                                             //Wait for 2 seconds
  digitalWrite(lightPin, HIGH);                        //Switches OFF the RELAY2
} //End of test_Relay(){ Switches ON for 2 seconds the RELAY -------------------





void EEPROMfirstTime() { //First time use, set values in EEPROM ****************
  EEPROM.write(1,   2);            //progHeater program 1=off 2=auto 3=on RELAY1
  EEPROM.write(2,  15);        //tempOn Temperature Celcius verwarming ON RELAY1
  EEPROM.write(3,  20);      //tempOff Temperature Celcius verwarming OFF RELAY1
  EEPROM.write(4,   2);               //progLed program 1=off 2=auto 3=on RELAY2
  EEPROM.write(5,  14);     //hoursLed Burning hours around noon groeiled RELAY2
  EEPROM.write(6,  10);                //ledRedBril Current brillance of RED LED
  EEPROM.write(7,   5);              //ledGreBril Current brillance of GREEN LED
  EEPROM.write(8,  10);               //ledBluBril Current brillance of BLUE LED
  EEPROM.write(9, 255);  //freqMeasSec Measurement every freqMeasSec seconds SYS
  EEPROM.write(10,  0);                                       //Versie Major SYS
  EEPROM.write(11,  1);                                       //Versie Minor SYS
  EEPROM.write(12,  1);                                    //Versie Revision SYS
  EEPROM.write(13,  4);                                      //Serial Number SYS
  //char    ssid[]       = "Ranonkel9";               //Network SSID (name) WIFI
  //char    pass[]       = "Kat14_-5";                   //Network password WIFI
} //Exit EEPROMfirstTime -------------------------------------------------------



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_ledOnBoard -----------------------------------------------------




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  -                           NC //
// SDA   -  27 - PC4 -18/A4- ADC4/SDA/PCINT12  -                           NC //
// AREF  -  21 - REF -     - AREF              -                              //
// GND   -  22 - GND -     - GND               -                              //
// 13    -  19 - PB5 -  13 - SCK/PCINT5        - SCK SD-card LED_BUILT_IN SPI //
// 12    -  18 - PB4 -  12 - MISO/PCINT4       - MISO SD-card             SPI //
// ~11   -  17 - PB3 -  11 - MOSI/OC2A/PCINT3  - MOSI SD-card         PWM SPI //
// ~10   -  16 - PB2 -  10 - SS/OC1B/PCINT2    - SS SD-card           PWM SPI //
// ~9    -  15 - PB1 -   9 - OC1A/PCINT1       - Wifi RX geel             PWM //
// 8     -  14 - PB0 -   8 - PCINT0/CLK0/ICP1  - DS1820 Temperature       DIO //
//                                                                            //
// CONNECTIONS RAILS TOP RIGHT: DIGITAL PWM<~> ****************************** //
// 7     -  13 - PD7 -   7 - PCINT23/AIN1      -                          DIO //
// ~6    -  12 - PD6 -   6 - PCINT22/OCA0/AIN0 - LED red                  PWM //
// ~5    -  11 - PD5 -   5 - PCINT21/OC0B/T1   - LED green                PWM //
// 4     -   6 - PD4 -   4 - PCINT20/XCK/T0    - Relais 1                 INT //
// ~3    -   5 - PD3 -   3 - PCINT19/OC2B/INT1 - LED blue                 PWM //
// ~2    -   4 - PD2 -   2 - PCINT18/INT0      - Relais 2                 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               -                          VCC //
// RES   -   1 - RES -     - PCINT14/RESET     -                          RES //
// 3.3V  -     -     -     -                   -                              //
// 5V    -     -     -     -                   -                              //
// GND   -     -     -     -                   -                              //
// GND   -     -     -     -                   -                              //
// Vin   -     -     -     -                   -                              //
//                                                                            //
// CONNECTIONS RAILS BOTTOM RIGHT: ANALOG IN ******************************** //
// A0    -  23 - PC0 -A0/14- ADC0/PCINT8       -                          ADC //
// A1    -  24 - PC1 -A1/15- ADC1/PCINT9       -                          ADC //
// A2    -  25 - PC2 -A2/16- ADC2/PCINT10      -                          ADC //
// A3    -  26 - PC3 -A3/17- ADC3/PCINT12      -                          ADC //
// A4    -  27 - PC4 -A4/18- ADC4/SDA/PCINT12  - Clock DS1307             TWI //
// A5    -  28 - PC5 -A5/19- ADC5/SCL/PCINT13  - Clock DS1307             TWI //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////




////////////////////////////////////////////////////////////////////////////////
// EEPROM MEMORY MAP:                                                         //
// Start End  Number Description                                              //
// 0000  0000    1        Never use this memory location to be AVR compatible //
// 0001  0001    1   VERLICHTING hobbyLightProg: 1=off 2=on 3=auto     RELAY1 //
// 0002  0002    1     If LDR reaches this kasLightON*10 switch        RELAY1 //
// 0003  0003    1     kasLightSecs*10 werkverlichting on              RELAY1 //
// 0004  0004    1   VERWARMING hobbyHeatProg: 1=off 2=on 3=auto       RELAY2 //
// 0005  0005    1     Celsius hobbyHeatON/10 verwarming switch on     RELAY2 //
// 0006  0006    1     Celsius hobbyHeatOFF/10 verwarming switch off   RELAY2 //
////////////////////////////////////////////////////////////////////////////////



////////////////////////////////////////////////////////////////////////////////
// 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  //
////////////////////////////////////////////////////////////////////////////////
//345678911234567892123456789312345678941234567895123456789612345678971234567898


/*
void writeSDdata() { //Write the statistical data to the SD card ***************
  analogWrite(ledRedPin, 255);                //Red HIGH=on, LOW=off activityLED
  if (SD.begin(SDssPin)){ //Initialiseer SPI verbinding, bij mislukking sla over
    myFile = SD.open(filename, FILE_WRITE);       //Open or create file to write
    myFile.print (klokTime);                              //Start with timestamp
    myFile.print (" ");                         //Print a space to separate data
    myFile.print (tempDS18B20);                        //Add temperature DS18B20
    myFile.print (" ");                         //Print a space to separate data
    myFile.print (ledRedStatus);                        //Show on SERIAL MONITOR
    myFile.print (" ");                         //Print a space to separate data
    myFile.print (ledGreStatus);                        //Show on SERIAL MONITOR
    myFile.print (" ");                         //Print a space to separate data
    myFile.print (ledBluStatus);                        //Show on SERIAL MONITOR
    myFile.print (" ");                         //Print a space to separate data
    myFile.print (ledRedBril);                          //Show on SERIAL MONITOR
    myFile.print (" ");                         //Print a space to separate data
    myFile.print (ledGreBril);                          //Show on SERIAL MONITOR
    myFile.print (" ");                         //Print a space to separate data
    myFile.print (ledBluBril);                          //Show on SERIAL MONITOR
    myFile.print (" ");                         //Print a space to separate data
    myFile.print (progHeater);         //VERWARMINGSMAT 1=off 2=auto 3=on RELAY1
    myFile.print (" ");                         //Print a space to separate data
    myFile.print (heaterStatus);//Status HIGH=off, LOW=on VERWARMINGSMAT RELAIS1
    myFile.print (" ");                         //Print a space to separate data
    myFile.print (tempOn);            //Temperature Celcius verwarming ON RELAY1
    myFile.print (" ");                         //Print a space to separate data
    myFile.print (tempOff);          //Temperature Celcius verwarming OFF RELAY1
    myFile.print (" ");                         //Print a space to separate data
    myFile.print (progLed);          //GROEIVERLICHTING 1=off 2=aut 3=off RELAY2
    myFile.print (" ");                         //Print a space to separate data
    myFile.print (lightStatus);   //Status 1=off, 0=on  GROEIVERLICHTING RELAIS2
    myFile.print (" ");                         //Print a space to separate data
    myFile.print (hoursLed);         //Burning hours around noon groeiled RELAY2
    myFile.print (" ");                         //Print a space to separate data
    myFile.println (freqMeasSec);                       //Show on SERIAL MONITOR
    myFile.close();                              //Poppetje gezien, kastje dicht
  }//End of if (SD.begin(SDssPin))
  digitalWrite(ledRedPin, LOW);               //Red HIGH=on, LOW=off activityLED
} //Exit writeSDdata -----------------------------------------------------------


void spawnData() { //Export the data of this program to a PC through RS232 *****
  Serial.print (klokTime);    //Reset the datastring and add temperature DS18B20
  Serial.print (" ");                           //Print a space to separate data
  Serial.print (tempDS18B20); //Reset the datastring and add temperature DS18B20
  Serial.print (" ");                           //Print a space to separate data
  Serial.print (ledRedStatus);                          //Show on SERIAL MONITOR
  Serial.print (" ");                           //Print a space to separate data
  Serial.print (ledGreStatus);                          //Show on SERIAL MONITOR
  Serial.print (" ");                           //Print a space to separate data
  Serial.print (ledBluStatus);                          //Show on SERIAL MONITOR
  Serial.print (" ");                           //Print a space to separate data
  Serial.print (ledRedBril);                            //Show on SERIAL MONITOR
  Serial.print (" ");                           //Print a space to separate data
  Serial.print (ledGreBril);                            //Show on SERIAL MONITOR
  Serial.print (" ");                           //Print a space to separate data
  Serial.print (ledBluBril);                            //Show on SERIAL MONITOR
  Serial.print (" ");                           //Print a space to separate data
  Serial.print (progHeater);           //VERWARMINGSMAT 1=off 2=auto 3=on RELAY1
  Serial.print (" ");                           //Print a space to separate data
  Serial.print (heaterStatus);  //Status HIGH=off, LOW=on VERWARMINGSMAT RELAIS1
  Serial.print (" ");                           //Print a space to separate data
  Serial.print (tempOn);              //Temperature Celcius verwarming ON RELAY1
  Serial.print (" ");                           //Print a space to separate data
  Serial.print (tempOff);            //Temperature Celcius verwarming OFF RELAY1
  Serial.print (" ");                           //Print a space to separate data
  Serial.print (progLed);            //GROEIVERLICHTING 1=off 2=aut 3=off RELAY2
  Serial.print (" ");                           //Print a space to separate data
  Serial.print (lightStatus);     //Status 1=off, 0=on  GROEIVERLICHTING RELAIS2
  Serial.print (" ");                           //Print a space to separate data
  Serial.print (hoursLed);           //Burning hours around noon groeiled RELAY2
  Serial.print (" ");                           //Print a space to separate data
  Serial.println (freqMeasSec);                         //Show on SERIAL MONITOR

  //Serial.print (" ");                         //Print a space to separate data
  //currentData += versionMaj;                                //Versie Major SYS
  //Serial.print (" ");                         //Print a space to separate data
  //currentData += versionMin;                                //Versie Minor SYS
  //Serial.print (" ");                         //Print a space to separate data
  //currentData += versionRev;                             //Versie Revision SYS
  //Serial.print (" ");                         //Print a space to separate data
  //Serial.println (serialNum);                              //Serial Number SYS
} //Exit spawnData -------------------------------------------------------------

*/



/*
void readClock() { //Read the current time into the object from DS1307 *********
  DateTime now = rtc.now();  //Read the current time into the object from DS1307
  strncpy(buf,"YYYY-MM-DD hh:mm:ss\0",100);  //Format string for the time DS1307
  klokTime = now.format(buf);       //Format the timestap into a variable DS1307
  strncpy(buf,"hh\0",100);              //Format string for the time VERLICHTING
  tmp2 = now.format(buf);      //Format the timestap into a variable VERLICHTING
  currenthour = tmp2.toInt();       //Convert to value for switching VERLICHTING
} //Exit readClock -------------------------------------------------------------
*/
/*
//if (Serial.available() > 0) { //Check bytes received, -1 is empty buffer RS232
//    receiveStr = Serial.readStringUntil('\r'); //Read until CR Carriage Return
    commandByte =  receiveStr.charAt(0);                      //Retreive command

    switch (commandByte) {           //Go to the according procedure / menu item

     case 62: //************* Menu item > => Adjust clock with given time DS1307
          klokTime = "";     //Formatteer zowel nieuw antwoord alsook zetformaat
            tmp = receiveStr.substring(2, 6);         //Extract jaar naar string
            klokTime = tmp;                         //Voeg toe aan http response
            klokTime += "-";                        //Voeg toe aan http response
            int jaar = tmp.toInt();            //Maak een bruikbare klok setting

            tmp = receiveStr.substring(7, 9);        //Extract maand naar string
            klokTime += tmp;
            klokTime += "-";
            int maand = tmp.toInt();           //Maak een bruikbare klok setting

            tmp = receiveStr.substring(10, 12);        //Extract dag naar string
            klokTime += tmp;
            klokTime += " ";
            int dag = tmp.toInt();             //Maak een bruikbare klok setting
              
            tmp = receiveStr.substring(13, 15);        //Extract uur naar string
            klokTime += tmp;
            klokTime += ":";
            int uur = tmp.toInt();             //Maak een bruikbare klok setting

            tmp = receiveStr.substring(16, 18);     //Extract minuut naar string
            klokTime += tmp;
            klokTime += ":";
            int minuut = tmp.toInt();          //Maak een bruikbare klok setting

            tmp = receiveStr.substring(19, 21);    //Extract seconde naar string
            klokTime += tmp;
            int seconde = tmp.toInt();         //Maak een bruikbare klok setting

            rtc.adjust(DateTime(jaar, maand, dag, uur, minuut, seconde));
            // <----------------------SET TIME
      break; //End of case 62:               Adjust clock with given time DS1307

      
      case 49: //************************************* Menu item 1 => LED RED ON
      ledRedStatus = ledRedBril;                          //Refresh the LED DATA
      analogWrite(ledRedPin,ledRedBril);                         //Switch LED ON
      break; //case 49:                                Menu item 1 => LED RED ON

      case 50: //************************************ Menu item 2 => LED RED OFF
      ledRedStatus = 0;                                   //Refresh the LED DATA
      analogWrite(ledRedPin,0);                                 //Switch LED OFF
      break; //case 48:                               Menu item 2 => LED RED OFF

      case 51: //*********************************** Menu item 3 => LED GREEN ON
      ledGreStatus = ledGreBril;                          //Refresh the LED DATA
      analogWrite(ledGrePin,ledGreBril);                         //Switch LED ON
      break; //case 51:                              Menu item 3 => LED GREEN ON

      case 52: //********************************** Menu item 4 => LED GREEN OFF
      ledGreStatus = 0;                                   //Refresh the LED DATA
      analogWrite(ledGrePin,0);                                 //Switch LED OFF
      break; //case 52:                             Menu item 4 => LED GREEN OFF

      case 53: //************************************ Menu item 5 => LED BLUE ON
      ledBluStatus = ledBluBril;                          //Refresh the LED DATA
      analogWrite(ledBluPin,ledBluBril);                         //Switch LED ON
      break; //case 53:                               Menu item 5 => LED BLUE ON

      case 54: //*********************************** Menu item 6 => LED BLUE OFF
      ledBluStatus = 0;                                   //Refresh the LED DATA
      analogWrite(ledBluPin,0);                                 //Switch LED OFF
      break; //case 54:                              Menu item 6 => LED BLUE OFF

      case 55: //*********************** Menu item 7 => SHOW TEMPERATURE DS18B20
      //spawnData();     //Export the data of this program to a PC through RS232
      break; //case 55:                  Menu item 7 => SHOW TEMPERATURE DS18B20

      case 56: //****************************** Menu item 8 => SWITCH HEATER OFF
      heaterStatus = HIGH;                             //Refresh the return DATA
      digitalWrite(heaterPin,HIGH);                          //Switch HEATER OFF
      break; //case 56:                         Menu item 8 => SWITCH HEATER OFF

      case 57: //******************************* Menu item 9 => SWITCH HEATER ON
      heaterStatus = LOW;                              //Refresh the return DATA
      digitalWrite(heaterPin,LOW );                           //Switch HEATER ON
      break; //case 57:                          Menu item 9 => SWITCH HEATER ON

      case 58: //************************* Menu item : => SWITCH VERLICHTING OFF
      lightStatus = HIGH;                              //Refresh the return DATA
      digitalWrite(lightPin,HIGH);                      //Switch VERLICHTING OFF
      break; //case 58:                    Menu item : => SWITCH VERLICHTING OFF

      case 59: //************************** Menu item ; => SWITCH VERLICHTING ON
      lightStatus = LOW;                               //Refresh the return DATA
      digitalWrite(lightPin,LOW );                       //Switch VERLICHTING ON
      break; //case 59:                     Menu item ; => SWITCH VERLICHTING ON

      case 60: //******************************* Menu item < => BRIGHTER LED RED
      ledRedBril++;                                      //Increase the LED DATA
      //EEPROM.write(6, ledRedBril);   //ledRedBril Current brillance of RED LED
      analogWrite(ledRedPin,ledRedBril);                         //Switch LED ON
      break; //case 60:                          Menu item < => BRIGHTER LED RED

      case 61: //************************************ Menu item = => DIM LED RED
      ledRedBril--;                                      //Increase the LED DATA
      //EEPROM.write(6, ledRedBril);   //ledRedBril Current brillance of RED LED
      analogWrite(ledRedPin,ledRedBril);                               //Dim LED
      break; //case 61:                               Menu item = => DIM LED RED

      case 63: //************************************ Menu item ? => DIM LED RED
      analogWrite(ledRedPin, 255);            //Red HIGH=on, LOW=off activityLED

      if (SD.begin(SDssPin)){                      //Initialiseer SPI verbinding
        myFile = SD.open(filename);                          //Open file to read
        while (myFile.available()) {
          tmp1 = myFile.read();
          Serial.print(char(tmp1));
        }
        myFile.close();                          //Poppetje gezien, kastje dicht
      }//End of if (SD.begin(SDssPin))

      digitalWrite(ledRedPin, LOW);           //Red HIGH=on, LOW=off activityLED
      break; //case 63:                               Menu item = => DIM LED RED

    case 62: //************** Menu item > => Adjust clock with given time DS1307
          klokTime = "";     //Formatteer zowel nieuw antwoord alsook zetformaat
            tmp = receiveStr.substring(2, 6);         //Extract jaar naar string
            klokTime = tmp;                         //Voeg toe aan http response
            klokTime += "-";                        //Voeg toe aan http response
            int jaar = tmp.toInt();            //Maak een bruikbare klok setting

            tmp = receiveStr.substring(7, 9);        //Extract maand naar string
            klokTime += tmp;
            klokTime += "-";
            int maand = tmp.toInt();           //Maak een bruikbare klok setting

            tmp = receiveStr.substring(10, 12);        //Extract dag naar string
            klokTime += tmp;
            klokTime += " ";
            int dag = tmp.toInt();             //Maak een bruikbare klok setting

            tmp = receiveStr.substring(13, 15);        //Extract uur naar string
            klokTime += tmp;
            klokTime += ":";
            int uur = tmp.toInt();             //Maak een bruikbare klok setting

            tmp = receiveStr.substring(16, 18);     //Extract minuut naar string
            klokTime += tmp;
            klokTime += ":";
            int minuut = tmp.toInt();          //Maak een bruikbare klok setting

            tmp = receiveStr.substring(19, 21);    //Extract seconde naar string
            klokTime += tmp;
            int seconde = tmp.toInt();         //Maak een bruikbare klok setting

            rtc.adjust(DateTime(jaar, maand, dag, uur, minuut, seconde));
            // <----------------------SET TIME
      break; //End of case 62:               Adjust clock with given time DS1307
      */