////////////////////////////////////////////////////////////////////////////////
// Name:         ESP01-3                                                      //
// Platform:     Arduino Mega 2560                                            //
// Created by:   HARB rboek2@gmail.com July 2018 GPL copyrights               //
// http://robotigs.nl/robotigs/includes/bots_header.php?idbot=7               //
// This robot is built to replace the 2017 Uno robot in the greenhouse        //
// As outputs the following modules are mounted:                              //
// - Standard Arduino Onboard LED (PWM)                                       //
// - 3 color LED (PWM)                                                        //
// - Activ loudspeaker                                                        //
// - 220 Vac Relay                                                            //
// As inputs the following modules are mounted:                               //
// - DS1307 Real Time Clock                                                   //
// - DHT22 air temperature and air humidity sensor                            //
// - LED                                                                      //
// - CJMCU soil huidity sensor (TWI)                                          //
// For communications are mounted:                                            //
// - Standard Serial Monitor output                                           //
// - ESP-01 Wifi unit                                                         //
//                                                                            //
// Connect ESP-01 to your Arduino:                                            //
// Yellow = Arduino RX1 19 = ESP-01 TX                                        //
// Blue   = Arduino TX1 18 = ESP-01 RX                                        //
// Connect your Arduino to your PC and open the serial monitor.               //
// AT commands AT version:1.1.0.0(May 11 2016 18:09:56)                       //
////////////////////////////////////////////////////////////////////////////////


// 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 <DHT.h> //Needed for DHT22 and DHT11 Temperature and humidity sensors
  #include <Wire.h>                                         //Two Wire Interface
  #include <RTClib.h>                           //connected via I2C and Wire lib
  #include <WiFiEsp.h>                   //https://github.com/bportaluri/WiFiEsp

  //#include <WiFiEspUdp.h>
  //#include <WiFiEspClient.h>
  //#include <WiFiEspServer.h>

// Define precompiler variables -----------------(Runs faster & doesn`t use RAM)
  // Define PINS ---------------------------------------------------------------
  #define buzAct 14             //Define which I/O pin connects the activ BUZZER
  #define ledRedPin  44            //3 Colour LED, which PWM pin connects redLED
  #define ledBluPin  45        //3 Colour LED, to which PWM pin connects blueLED
  #define ledGrePin  46       //3 Colour LED, to which PWM pin connects greenLED
  #define DHTPIN 47                                //What DIO pin connects DHT22
  #define DHTTYPE DHT22       //What sensor is connected (AM2302) (AM2321) DHT22
  #define Relay1Pin  48                   //220Vac switch DIO pin connects RELAY
  #define ldrPin A15             //Define to which DA converter pin connects LDR


  //Define VARIABLES -----------------------------------------------------------
  bool ledOnBoardVal = LOW;   //You can chose HIGH-on or LOW-off for LED_BUILTIN
  const int bSize = 20;                      //Needed for internet communication
  String inStri = "No answer received";  //Receive string internet communication
  byte msWait = 1;                      //Test your patience during the LED test
  byte brillance = 0;           //Brightness of any color, just to test LEDs PWM
  char buf[100];                  //Needed to display the DS1307 date/time stamp
  String timestamp;
  float grenairtmp1;                          //Temperature as measured by DHT22
  float grenairhum1;                             //Humidity as measured by DHT22
  word ldrVal =   0;                    //Contains last measurement (0-1023) LDR
  word grensolhum1;                         //Soil humidity as measured by Chirp
  word grensoltmp1;                           //Temperature as measured by Chirp
  word grensollum1;                           //Solar power as measured by Chirp

  char ssid[] = "Ranonkel9";                         // Network SSID (name) WIFI
  char pass[] = "Kat14_-5";                              //Network password WIFI
  int status = WL_IDLE_STATUS;
  int ledStatus = LOW;


  // Initialize OBJECTS --------------------------------------------------------
  DHT dht(DHTPIN, DHTTYPE);                     //Initialize sensor object DHT22
  DS1307 rtc;                         //Initialize Real Time Clock object DS1307
  WiFiEspServer server(80);                                //Start the webserver
  RingBuffer buf2(8); //Ringbuffer increases speed and reduces memory allocation
//END OF PRECOMPILER OPTIONS ---------------------------------------------------





void setup() { // **************************************************************
  disable_jtag();              //Disable jtag to free port C, enabled by default
  
  pinMode(LED_BUILTIN, OUTPUT);  //Arduino boards contain an onboard LED_BUILTIN
  pinMode(buzAct, OUTPUT);                    //Set this pin as output to BUZZER
  pinMode(ledRedPin, OUTPUT);        //Make the RED LED connection an output pin
  pinMode(ledBluPin, OUTPUT);                //Set this pin as output to blueLED
  pinMode(ledGrePin, OUTPUT);               //Set this pin as output to greenLED
  pinMode(Relay1Pin, OUTPUT);                  //Set this pin as output to RELAY
  digitalWrite(Relay1Pin, LOW);                         //Switches OFF the RELAY  
  
  Wire.begin();                        //Start the Two Wire Interface object I2C
  dht.begin();                               //Start sensor object running DHT22
  writeI2CRegister8bit(0x20, 6);      //Reset sensor to tell it is a slave DHT22
  rtc.begin();                                 //Start the object running DS1307
  //rtc.adjust(DateTime(__DATE__, __TIME__));      //Set to time compiled DS1307

  Serial.begin(9600);        //Nothing more needed for the Serial Monitor RSR232
  Serial1.begin(115200);                        //RS232 Speed is preset at ESP01
  Serial1.setTimeout(1000);  //Max wait in ms before returning as an error ESP01

  //test_RELAY();                          //Switches ON for 2 seconds the RELAY
  //test_ESP01();                                   //Test the Wifi module ESP01
  
  WiFi.init(&Serial1);    // initialize ESP module

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  // attempt to connect to WiFi network
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  Serial.println("You're connected to the network");
  printWifiStatus();
  
  // start the web server on port 80
  server.begin();
  
  test_LEDs();            //PWM fade in and fade out for all 4 LEDs on board LED
  beep(10);                       //Create a test beep with KY-012 active BUZZER
  Serial.println("Setup completed");     //Show the user the setup is done RS232
} //End of setup ---------------------------------------------------------------



void loop() { //KEEP ON RUNNING THIS LOOP FOREVER  *****************************

 WiFiEspClient client = server.available();  // listen for incoming clients

  if (client) {                               // if you get a client,
    Serial.println("New client");             // print a message out the serial port
    buf2.init();                               // initialize the circular buffer
    while (client.connected()) {              // loop while the client's connected
      if (client.available()) {               // if there's bytes to read from the client,
        char c = client.read();               // read a byte, then
        buf2.push(c);                          // push it to the ring buffer

        // printing the stream to the serial monitor will slow down
        // the receiving of data from the ESP filling the serial buffer
        //Serial.write(c);
        
        // you got two newline characters in a row
        // that's the end of the HTTP request, so send a response
        if (buf2.endsWith("\r\n\r\n")) {
          sendHttpResponse(client);
          break;
        }

        // Check to see if the client request was "GET /H" or "GET /L":
        if (buf2.endsWith("GET /H")) {
          Serial.println("Turn led ON");
          ledStatus = HIGH;
          digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
        }
        else if (buf2.endsWith("GET /L")) {
          Serial.println("Turn led OFF");
          ledStatus = LOW;
          digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
        }
      }
    }
    
    // close the connection
    client.stop();
    Serial.println("Client disconnected");
  }
  /*
  beep(1);                                  //Tell the world we are awake BUZZER
  analogWrite(ledBluPin, 50);                //Blue HIGH=on, LOW=off activityLED  
  // 1) FIRST STEP IS TO READ ALL SENSORS --------------------------------------
  grenairtmp1 = dht.readTemperature();       //Read temperature as Celsius DHT22
  grenairhum1 = dht.readHumidity();//Reading sensor takes 250 milliseconds DHT22
  DateTime now = rtc.now();  //Read the current time into the object from DS1307
  strncpy(buf,"YYYY-MM-DD hh:mm:ss\0",100);   //Formatstring for the time DS1307
  timestamp = now.format(buf);      //Format the timestap into a variable DS1307
  ldrVal = analogRead(ldrPin);                      //Read voltage on pin A0 LDR
  // 2) SECOND STEP IS TO CALCULATE THE DESIRED SETTING OF THE SWITCHES --------
    //calculate_lightswitch(); //Calculate lightSwitch ON or OFF according clock
  // 3) THIRD STEP IS TO SET THE SWITCHES AS DESIRED ---------------------------
    //switch_light();  //Switch the LED lighting ON or OFF according lightSwitch
  // 4) LAST STEP IS TO COMMUNICATE TO THE SERIAL PORT AND FINISH LOOP ---------
  showMonitor();                  //Shows all values at the serial monitor RS232
  // 5) RETURN TO START AGAIN --------------------------------------------------
  toggle_ledOnBoard();           //Toggles the LED_BUILTIN  ON or OFF onboardLED
  digitalWrite(ledBluPin, LOW);              //Blue HIGH=on, LOW=off activityLED
  delay (60000);                                        //Wait idle for a minute
  */
} //End of void loop() ----------------------- KEEP ON RUNNING THIS LOOP FOREVER




void sendHttpResponse(WiFiEspClient client)
{
  // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
  // and a content-type so the client knows what's coming, then a blank line:
  client.println("HTTP/1.1 200 OK");
  client.println("Content-type:text/html");
  client.println();
  
  // the content of the HTTP response follows the header:
  client.print("The LED is ");
  client.print(ledStatus);
  client.println("<br>");
  client.println("<br>");
  
  client.println("Click <a href=\"/H\">here</a> turn the LED on<br>");
  client.println("Click <a href=\"/L\">here</a> turn the LED off<br>");
  
  // The HTTP response ends with another blank line:
  client.println();
}

void printWifiStatus()
{
  // print the SSID of the network you're attached to
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print where to go in the browser
  Serial.println();
  Serial.print("To see this page in action, open a browser to http://");
  Serial.println(ip);
  Serial.println();
}

void Test2(void) { //Set mode and connect to AP ********************************
  /*
  Serial.println("AT+CWMODE=1 Set mode 1=STA 2=AP 3=BOTH **");       //Set modus
  Serial1.println("AT+CWMODE=1");                   //Set Wifi mode to 1=station
  readESP01();                        //Receives data from the ESP01 Wifi module
  Serial.println(inStri);                          //Show the answer to the user
  Serial.println(" ");                                        //Print empty line

  Serial.println("AT+RST **");                 //Restart after a change in modus
  Serial1.setTimeout(5000);        //Max wait in ms before returning as an error
  Serial1.println("AT+RST");                   //Restart is nodig na mode setten
  readESP01();                        //Receives data from the ESP01 Wifi module
  Serial.println(inStri);                          //Show the answer to the user
  Serial.println(" ");                                        //Print empty line
  */
  
  //Serial.println("AT+CWMODE? Show current WifiMode **"); //ANSWERS:+CWMODE:1+ OK
  Serial1.println("AT+CWMODE?");                       //Query current Wifi mode
  readESP01();                        //Receives data from the ESP01 Wifi module
  Serial.println(inStri);                          //Show the answer to the user
  Serial.println(" ");                                        //Print empty line

  //Serial.println("AT+CWLAP Lists Access Points **");         //ANSWERS: LIST +OK
  Serial1.println("AT+CWLAP");          //List currently Available access Points
  Serial1.setTimeout(5000);        //Max wait in ms before returning as an error
  readESP01();                        //Receives data from the ESP01 Wifi module
  Serial.println(inStri);                          //Show the answer to the user
  Serial.println(" ");                                        //Print empty line

  //Serial.println("AT+CIFSR Print IP address **");          //ANSWERS: IP address
  Serial1.println("AT+CIFSR");                           //Show IP address ESP01
  readESP01();                        //Receives data from the ESP01 Wifi module
  Serial.println(inStri);                          //Show the answer to the user
  Serial.println(" ");                                        //Print empty line

  //Serial.println("AT+CWJAP? Connected to an Access point? **");     //No AP + OK
  Serial1.println("AT+CWJAP?");                      //List current Access Point
  readESP01();                        //Receives data from the ESP01 Wifi module
  Serial.println(inStri);                          //Show the answer to the user
  Serial.println(" ");                                        //Print empty line
  
  /*
  Serial.println("AT+CWJAP= Connect to Access point **");       //ANSWERS: ERROR
  Serial1.print("AT+CWJAP=");                             //Connect Access Point
  Serial1.print('"');
  Serial1.print("Ranonkel9_EXT");                                         //SSID
  Serial1.print('"');
  Serial1.print(",");
  Serial1.print('"');
  Serial1.print("Kat14_-5");                                          //Password
  Serial1.println('"');
  readESP01();                        //Receives data from the ESP01 Wifi module
  Serial.println(inStri);                          //Show the answer to the user
  Serial.println(" ");                                        //Print empty line

  Serial.println("AT+CIFSR Print IP address **");          //ANSWERS: IP address
  Serial1.println("AT+CIFSR");                           //Show IP address ESP01
  readESP01();                        //Receives data from the ESP01 Wifi module
  Serial.println(inStri);                          //Show the answer to the user
  Serial.println(" ");                                        //Print empty line
  
  Serial.println("AT+CWJAP? Connected to an Access point? **");     //No AP + OK
  Serial1.println("AT+CWJAP?");                      //List current Access Point
  readESP01();                        //Receives data from the ESP01 Wifi module
  Serial.println(inStri);                          //Show the answer to the user
  Serial.println(" ");                                        //Print empty line
  */
} //End of Test: 2 Set mode and c






void test_ESP01(){ //Test the Wifi module ESP01 ********************************
  Test1();                                   //AT system test & AT+GMR version
  //Test2();                                        //Set mode and connect to AP
  //Test3();                                           //Test modes of the ESP01
} //End of test_ESP01(){ //Test the Wifi module ESP01 --------------------------



void readESP01(){ //Receives data from the ESP01 Wifi module *******************
  inStri = "";                                     //Reset string to be received
  inStri = Serial1.readStringUntil('O');             //Read incoming characters
} //End of readESP01 Receives data from the ESP01 Wifi module ------------------




////////////////////////////////////////////////////////////////////////////////
// PIN ALLOCATIONS TABLE ARDUINO MEGA 2560                                    //
// Board  -Atmel- PIN - IDE - Function          - External Connection    FUNC //
//                                                                            //
// CONNECTIONS RAILS TOP LEFT: DIGITAL PWM<~> ******************************* //
// SCL    -  28 - PC5 -19/A5- ADC5/SCL/PCINT13  - DS1307 SCL orange       TWI //
// SDA    -  27 - PC4 -18/A4- ADC4/SDA/PCINT12  - DS1307 SDA white        TWI //
// AREF   -  31 - REF -     - AREF              -                         REF //

// 13 PWM -  26 - PB7 -  13 - OC0A/OC1C/PCINT17 - LED Arduino LED_BUILTIN PWM //
// 12 PWM -  18 - PB6 -  12 - OC1B/PCINT16      -                         PWM //
// 11 PWM -  17 - PB3 -  11 - MOSI/OC2A/PCINT3  -                         PWM //
// 10 PWM -  16 - PB2 -  10 - SS/OC1B/PCINT2    -                         PWM //
//  9 PWM -  15 - PB1 -   9 - OC1A/PCINT1       -                         PWM //
//  8 PWM -  14 - PB0 -   8 - PCINT0/CLK0/ICP1  -                         DIO //
//                                                                            //
// CONNECTIONS RAILS TOP MIDDLE: DIGITAL PWM<~> ***************************** //
//  7 PWM -  13 - PD7 -   7 - PCINT23/AIN1      -                         PWM //
//  6 PWM -  12 - PD6 -   6 - PCINT22/OCA0/AIN0 -                         PWM //
//  5 PWM -  11 - PD5 -   5 - PCINT21/OC0B/T1   -                         PWM //
//  4 PWM -   6 - PD4 -   4 - PCINT20/XCK/T0    -                         PWM //
//  3 PWM -   5 - PD3 -   3 - PCINT19/OC2B/INT1 -                         PWM //
//  2 PWM -   4 - PD2 -   2 - PCINT18/INT0      -                         INT //
//  1 TX0 -   3 - PD1 -   1 - PCINT17/TXD       - Serial monitor          TX0 //
//  0 RX0 -   2 - PD0 -   0 - PCINT16/RCD       - Serial Monitor          RC0 //
//                                                                            //
// CONNECTIONS RAILS TOP RIGHT: DIGITAL PWM<~> ****************************** //
// 14 TX3 -  13 - PD7 -   7 - PCINT23/AIN1      - Activ buzzer orange     DIO //
// 15 RX3 -  12 - PD6 -   6 - PCINT22/OCA0/AIN0 -                         PWM //
// 16 TX2 -  11 - PD5 -   5 - PCINT21/OC0B/T1   -                         TX2 //
// 17 RX2 -   6 - PD4 -   4 - PCINT20/XCK/T0    -                         RX2 //
// 18 TX1 -   5 - PD3 -   3 - PCINT19/OC2B/INT1 - Transmit to ESP01 blue  INT //
// 19 RX1 -   4 - PD2 -   2 - PCINT18/INT0      - Rec from ESP01 yellow   INT //
// 20 SDA -   3 - PD1 -   1 - PCINT17/TXD       -                         TWI //
// 21 SCL -   2 - PD0 -   0 - PCINT16/RCD       -                         TWI //
//                                                                            //
// 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 CENTER: 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  -                         TWI //
// A5     -  28 - PC5 -A5/19- ADC5/SCL/PCINT13  -                         TWI //
//                                                                            //
// CONNECTIONS RAILS BOTTOM RIGHT: ANALOG IN ******************************** //
// A08    -  89 - PK0 -     - ADC1 4/PCINT?     -                         ADC //
// A09    -  88 - PK1 -     - ADC15/PCINT?      -                         ADC //
// A10    -  87 - PK2 -     - ADC14/PCINT?      -                         ADC //
// A11    -  86 - PK3 -     - ADC15/PCINT?      -                         ADC //
// A12    -  85 - PK4 -     - ADC14/PCINT?      -                         ADC //
// A13    -  84 - PK5 -     - ADC15/PCINT?      -                         ADC //
// A14    -  83 - PK6 -     - ADC14/PCINT22     -                         ADC //
// A15    -  82 - PK7 -     - ADC15/PCINT23     - LDR purple              ADC //
//                                                                            //
// CONNECTIONS RAILS QUER RIGHT ********************************************* //
// Board  -Atmel- PIN - IDE - Function          - External Connection    FUNC //
// 32     -  58 - PC5 -     - DIO               -                         DIO //
// 44     -  40 - PL5 -     - OC5C              - 3 Color led Red         PWM //
// 45     -  39 - PL4 -     - OC5B              - 3 Color led Blue        PWM //
// 46     -  38 - PL3 -     - OC5A              - 3 Color led Green       PWM //
// 47     -  37 - PL2 -     - T5                - DHT22 one-wire white    DIO //
// 48     -  36 - PL1 -     - ICP5              - Relais 1 purple         DIO //
// 49     -  35 - PL0 -     - ICP4              -                         DIO //
// 50     -  22 - PB3 -     - MISO/PCINT3       -                         SPI //
// 51     -  21 - PB2 -     - MOSI/PCINT2       -                         SPI //
// 52     -  20 - PB1 -     - SCK/PCINT1        -                         SPI //
// 53     -  19 - PB1 -     - SS/PCINT0         -                         SPI //
// 54     -     - GND -     - GND               -                         GND //
// 55     -     - GND -     - GND               -                         GND //
////////////////////////////////////////////////////////////////////////////////
//345678911234567892123456789312345678941234567895123456789612345678971234567898
// EEPROM MEMORY MAP:                                                         //
// Start End  Number Description                                              //
// 0000  0000      1 Never use this memory location to be AVR compatible      //
////////////////////////////////////////////////////////////////////////////////
//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=1)         //
// 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  //
////////////////////////////////////////////////////////////////////////////////



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



void showMonitor(){ //Shows all values at the serial monitor RS232 *************
  Serial.print(timestamp);   //Print the DS1307 time in the desired format RS232
  Serial.print(" ");                                //Print an empty space RS232
  Serial.print("Temperatuur:");        //Print DHT22 to the serial monitor RS232
  Serial.print(grenairtmp1);           //Print DHT22 to the serial monitor RS232
  Serial.print(" Luchtvochtigheid:");  //Print DHT22 to the serial monitor RS232
  Serial.print(grenairhum1);           //Print DHT22 to the serial monitor RS232
  Serial.print(" LDRval:");              //Print LDR to the serial monitor RS232
  Serial.println(ldrVal);                //Print LDR to the serial monitor RS232
} //End of showMonitor(){ Shows all values at the serial monitor RS232 ---------


void Test1(void) { //AT system test & AT+GMR version ***************************
  Serial.println("AT: test if system works correctly: ** ");       //ANSWERS: OK
  Serial1.println("AT");                     //Test if AT system works correctly
  readESP01();                        //Receives data from the ESP01 Wifi module
  Serial.println(inStri);                          //Show the answer to the user
  Serial.println(" ");                                        //Print empty line

  Serial.print("AT+GMR COMMANDS are version: ** ");    //ANSWERS: Version number
  Serial1.println("AT+GMR");             //Show version info ESP8266 AT-software
  readESP01();                        //Receives data from the ESP01 Wifi module
  Serial.println(inStri);                          //Show the answer to the user
  Serial.println(" ");                                        //Print empty line
} //End of Test1: AT system test & AT+GMR version ------------------------------




unsigned int readI2CRegister16bit(int addr, int reg){ //Read any TWI register **
  Wire.beginTransmission(addr);
  Wire.write(reg);
  Wire.endTransmission();
  delay(20);
  Wire.requestFrom(addr, 2);
  unsigned int t = Wire.read() << 8;
  t = t | Wire.read();
  return t;
} //Exit readI2CRegister16bit --------------------------------------------------


void writeI2CRegister8bit(int addr, int value){  //Reset DHT22 sensor **********
  Wire.beginTransmission(addr);
  Wire.write(value);
  Wire.endTransmission();
} //Exit writeI2CRegister8bit --------------------------------------------------


void test_LEDs(void){ //PWM fade in and fade out for all 4 LEDs on board *******
  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
  
  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
} //Exit test_LEDs -------------------------------------------------------------


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


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