////////////////////////////////////////////////////////////////////////////////
// Name:       Couveuse1_2560_02_lanSDwifiClock                               //
//             02 = Adding Wifi (serial) and Clock(TWI)                       //
//             01 = LAN and SDcard test. Both are SPI.                        //
// http://robotigs.com/robotigs/includes/bots_header.php?idbot=17             //
//             Robot that controls Couveuse1                                  //
// Created by: HARB rboek2@gmail.com Januar 2020 GPL copyrights               //
// Platform:   Arduino Mega 2560                                              //
//             This program will not run on an Arduino Uno. The dynamic       //
//             memory is too small to store global variables.                 //
// Useful for testing a card when you're not sure whether its working or not. //
// Serial monitor needed to see the output of the test results.               //
// SD card basic test and network basic test. Both connected to SPI.          //
////////////////////////////////////////////////////////////////////////////////
// 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 //
// 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 //
// 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 //
// - SD card                                                                  //
//           http://robotigs.nl/robotigs/includes/parts_header.php?idpart=116 //
////////////////////////////////////////////////////////////////////////////////



// 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 <SPI.h>   //Serial Peripheral Interface requiered by software SD-CARD
              // http://robotigs.nl/robotigs/includes/parts_header.php?idpart=28
  #include <SD.h>                      //Include SD library software for SD-CARD
             // http://robotigs.nl/robotigs/includes/parts_header.php?idpart=116
  #include <EtherCard.h>                        //Librairy for Lan ENC28J60 unit
              //http://robotigs.nl/robotigs/includes/parts_header.php?idpart=313


  //Define PINS ----------------------------------------------------------------
  #define buzActPin    A0          //Define DIO output pin connects ACTIV BUZZER
  #define ledBluPin    46        //3 Colour LED, which PWM pin connects BLUE LED
  #define ledGrePin    45       //3 Colour LED, which PWM pin connects GREEN LED
  #define ledRedPin    44         //3 Colour LED, which PWM pin connects RED LED
  const int chipSelect = 49;//SPI Chip select LAN pin mut be 53, so SDcard is 49


  //Define LIBRARY variables ---------------------------------------------------
  Sd2Card card;        //Set up variables using the SD utility library functions
  SdVolume volume;     //Set up variables using the SD utility library functions
  SdFile root;         //Set up variables using the SD utility library functions
  //Define EEPROM variables ----------------------------------------------------
  //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
  //Define variables -----------------------------------------------------------
  static byte mymac[] = {0x00,0x01,0x02,0x03,0x04,0x16};      //For internet use
  String inStri = "No answer received";                     //Set receive string
  String striLine = "";

  String html           = "";                    //HTML Response preapaired WIFI
  int    bodyLength;                                   //HTML answer length WIFI
  //int    status         = WL_IDLE_STATUS;             //Status of the ESP01 WIFI
  char   ssid[]         = "Ranonkel9_EXT";            //Network SSID (name) WIFI
  char   pass[]         = "Kat14_-5";                    //Network password WIFI
  String commandStr     = "";               //Commands received by html INTERNET
  int    command        = 0;                //Which user command to perform WIFI
  int    value          = 0;             //Value that comes with the object WIFI

  String tempo          = "";                             //Can be used anywhere 
  int    tmp1;                                            //Can be used anywhere 
  int    tmp2;                                            //Can be used anywhere 


  //Initialize OBJECTS ---------------------------------------------------------
  uint8_t Ethernet::buffer[700];                //For internet communication use
  BufferFiller bfill;                                             //LAN ENC28J60
  DS1307 rtc;                         //Initialize Real Time Clock object DS1307
//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
  Serial1.begin(57600); //Nothing more needed for the Serial Monitor to function
  Serial1.setTimeout(1000);        //Max wait in ms before returning as an error
  pinMode(LED_BUILTIN, OUTPUT);  //Arduino boards contain an onboard LED_BUILTIN
  pinMode(buzActPin, OUTPUT);                 //Set this pin as output to BUZZER
  beep(10);                       //Create a test beep with KY-012 active BUZZER
  pinMode(ledRedPin, OUTPUT);                 //Set this pin as output to redLED
  pinMode(ledBluPin, OUTPUT);                //Set this pin as output to blueLED
  pinMode(ledGrePin, OUTPUT);               //Set this pin as output to greenLED

  //Start objects --------------------------------------------------------------
  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
  //WiFiEspServer server(80);                         //Start the webserver WIFI
  //RingBuffer buf2(8);     //Ringbuffer increases speed and reduces memory WIFI
  
  //Test hardware and software -------------------------------------------------
  testLAN();         //Ethernet obtain an IP-address by DHCP and show on monitor
  testSdCard();                   //Contact SD card and show all info on monitor
  testWIfi();                  //AT system test & AT+GMR version show on monitor
  Serial.println(" ");                   //Show the user the setup is done RS232
  Serial.println("Setup completed");     //Show the user the setup is done RS232
  Serial.println(" ");                   //Show the user the setup is done RS232
} //End of setup ---------------------------------------------------------------






void loop() { //KEEP ON RUNNING THIS LOOP FOREVER  *****************************
  readTime();        //Reading the time and format results into variables DS1307
  delay(5000);
} //End of void loop() ----------------------- KEEP ON RUNNING THIS LOOP FOREVER





void testWIfi(void) { //AT system test & AT+GMR version ************************
  Serial.println(" ");                   //Show the user the setup is done RS232
  Serial.print("AT: ");                                            //ANSWERS: OK
  Serial1.println("AT");                     //Test if AT system works correctly
  delay(50);                               //You can test your own patience here
  readESP01();                        //Receives data from the ESP01 Wifi module
  Serial.println(inStri);                          //Show the answer to the user
  
  Serial.print("AT+GMR: ");                            //ANSWERS: Version number
  Serial1.println("AT+GMR");             //Show version info ESP8266 AT-software
  delay(900);                              //You can test your own patience here
  readESP01();                        //Receives data from the ESP01 Wifi module
  Serial.println(inStri);                          //Show the answer to the user

  Serial.print("Set mode 1=STA 2=AP 3=BOTH: AT+CWMODE=1: ");         //Set modus
  Serial1.println("AT+CWMODE=1");                   //Set Wifi mode to 1=station
  delay(900);                              //You can test your own patience here
  readESP01();                        //Receives data from the ESP01 Wifi module
  Serial.println(inStri);                          //Show the answer to the user

  Serial.print("Restart 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
  delay(900);                              //You can test your own patience here
  readESP01();                        //Receives data from the ESP01 Wifi module
  Serial.println(inStri);                          //Show the answer to the user

  Serial.print("AT+CWMODE? Show current WifiMode: "); //ANSWERS:+CWMODE:1+ OK
  Serial1.println("AT+CWMODE?");                       //Query current Wifi mode
  delay(900);                              //You can test your own patience here
  readESP01();                        //Receives data from the ESP01 Wifi module
  Serial.println(inStri);                          //Show the answer to the user

  Serial.println("AT+CWLAP Lists Access Points **");         //ANSWERS: LIST +OK
  Serial1.println("AT+CWLAP");          //List currently Available access Points
  delay(4900);                             //You can test your own patience here
  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("Set to slower communication rate: ");      //General set ESP01
  Serial1.println("AT+UART_DEF=57600,8,1,0,0");      //Send command to the ESP01
  delay(900);                              //You can test your own patience here
  readESP01();                                     //Receive data from the ESP01
  Serial.println(inStri);                    //Show answer at the SERIAL MONITOR
  
  
} //End of testWIfi: AT system test & AT+GMR version ---------------------------



void readESP01(){ //Receives data from the ESP01 Wifi module ******************
  inStri = "";                                    //Reset string to be received
  while (Serial1.available()) {
    striLine = Serial1.readStringUntil('\n');                     //Read a line
    inStri = inStri + striLine;
    delay(300);                           //You can test your own patience here
  }
} //End of readESP01 Receives data from the ESP01 Wifi module -----------------







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
  Serial.print("Laatste meting: ");                        //Show the user RS232
  Serial.print(jaar);                                      //Show the user RS232
  Serial.print("/");                                       //Show the user RS232
  Serial.print(maand);                                     //Show the user RS232
  Serial.print("/");                                       //Show the user RS232
  Serial.print(dag);                                       //Show the user RS232
  Serial.print(" ");                                       //Show the user RS232
  Serial.print(uur);                                       //Show the user RS232
  Serial.print(":");                                       //Show the user RS232
  Serial.print(minuut);                                    //Show the user RS232
  Serial.print(":");                                       //Show the user RS232
  Serial.println(seconde);                                 //Show the user RS232
} //Exit readTime --------------------------------------------------------------






////////////////////////////////////////////////////////////////////////////////
// PIN ALLOCATIONS TABLE ARDUINO MEGA 2560                                    //
// Board  -Atmel- PIN - Function          - External Connection          FUNC //
//                                                                            //
// CONNECTIONS RAILS RIGHT TOP: DIGITAL PWM<~> ****************************** //
// SCL    -  43 - PD0 - SCL/INT0          - Clock DS1307 purple           TWI //
// SDA    -  44 - PD1 - SDA/INT1          - Clock DS1307 white            TWI //
// AREF   -  98 - REF - AREF              -                               REF //
// 13 PWM -  26 - PB7 - OC0A/OC1C/PCINT17 - LED Arduino LED_BUILTIN       PWM //
// 12 PWM -  25 - PB6 - OC1B/PCINT16      -                               PWM //
// 11 PWM -  24 - PB5 - OC1A/PCINT5       -                               PWM //
// 10 PWM -  23 - PB4 - OC2A/PCINT4       -                               PWM //
//  9 PWM -  18 - PH6 - OC2B              -                               PWM //
//  8 PWM -  17 - PH5 - OC4C              -                               PWM //
//                                                                            //
// CONNECTIONS RAILS RIGHT MIDDLE: DIGITAL PWM<~> *************************** //
//  7 PWM -  16 - PH4 - OC4B              -                               PWM //
//  6 PWM -  15 - PH3 - OC4A              -                               PWM //
//  5 PWM -   5 - PE3 - OC3A/AIN1         -                               PWM //
//  4 PWM -   1 - PG5 - OC0B              -                               PWM //
//  3 PWM -   7 - PE5 - OC3C/INT5         -                               INT //
//  2 PWM -   6 - PE4 - OC3B/INT4         -                               INT //
//  1 TX0 -   3 - PE1 - TXD0              - Serial monitor PC             TX0 //
//  0 RX0 -   2 - PE0 - RXD0/PCINT8       - Serial monitor PC             RX0 //
//                                                                            //
// CONNECTIONS RAILS RIGHT BOTTOM: DIGITAL PWM<~> *************************** //
// 14 TX3 -  64 - PJ1 - TXD3/PCINT10      -                               TX3 //
// 15 RX3 -  63 - PJ0 - RXD3/PCINT9       -                               RX3 //
// 16 TX2 -  13 - PH1 - TXD2              -                               TX2 //
// 17 RX2 -  12 - PH0 - RXD2              - DS18B20 Soil temperature      RX2 //
// 18 TX1 -  46 - PD3 - TXD1/INT3         - WIFI SERIAL               INT TX1 //
// 19 RX1 -  45 - PD2 - RXD1/INT2         - WIFI SERIAL               INT RX1 //
// 20 SDA -  44 - PD1 - SDA/INT1          - DS1307 I2C Clock white        TWI //
// 21 SCL -  43 - PD0 - SCL/INT0          - DS1307 I2C Clock purple       TWI //
//                                                                            //
// CONNECTIONS RAILS LEFT TOP: POWER **************************************** //
// NC     -     -     -                   - Not Connected                     //
// IOREF  -     -     - 3.3/5Vdc          - Outputs controller voltage        //
// 5V     -   7 - VCC - VCC               -                               VCC //
// RES    -   1 - RES - PCINT14/RESET     -                               RES //
// 3.3V   -     -     -                   -                                   //
// 5V     -     -     -                   -                                   //
// GND    -     -     -                   -                                   //
// GND    -     -     -                   -                                   //
// Vin    -     -     - 7/9Vdc power in   -                                   //
//                                                                            //
// CONNECTIONS RAILS LEFT MIDDLE : ANALOG IN ******************************** //
// A0     -  97 - PF0 - ADC0              -                               ADC //
// A1     -  96 - PF1 - ADC1              -                               ADC //
// A2     -  95 - PF2 - ADC2              -                               ADC //
// A3     -  94 - PF3 - ADC3              -                               ADC //
// A4     -  93 - PF4 - ADC4/TCK          -                               ADC //
// A5     -  92 - PF5 - ADC5/TMS          -                               ADC //
// A6     -  91 - PF6 - ADC6/TDO          -                               ADC //
// A7     -  90 - PF7 - ADC7/TDI          - Buzzer activ                  ADC //
//                                                                            //
// CONNECTIONS RAILS LEFT BOTTOM: ANALOG IN ********************************* //
// A8     -  89 - PK0 - ADC8/PCINT16      -                               ADC //
// A9     -  88 - PK1 - ADC9/PCINT17      -                               ADC //
// A10    -  87 - PK2 - ADC10/PCINT18     -                               ADC //
// A11    -  86 - PK3 - ADC11/PCINT19     -                               ADC //
// A12    -  85 - PK4 - ADC12/PCINT20     -                               ADC //
// A13    -  84 - PK5 - ADC13/PCINT21     -                               ADC //
// A14    -  83 - PK6 - ADC14/PCINT22     -                               ADC //
// A15    -  82 - PK7 - ADC15/PCINT23     -                               ADC //
//                                                                            //
// CONNECTIONS DOUBLE RAILS BOTTOM ****************************************** //
// Board  -Atmel- PIN - Function          - External Connection          FUNC //
// 5V     -     - 5Vdc- 5Vdc              -                               VCC //
// 5V     -     - 5Vdc- 5Vdc              -                               VCC //
// 22     -  78 - PA0 - AD0               -                               DIO //
// 23     -  77 - PA1 - AD1               -                               DIO //
// 24     -  76 - PA2 - AD2               -                               DIO //
// 25     -  75 - PA3 - AD3               -                               DIO //
// 26     -  74 - PA4 - AD4               -                               DIO //
// 27     -  73 - PA5 - AD5               -                               DIO //
// 28     -  72 - PA6 - AD6               -                               DIO //
// 29     -  71 - PA7 - AD7               -                               DIO //
// 30     -  60 - PC7 - A14               -                               DIO //
// 31     -  59 - PC6 - A15               -                               DIO //
// 32     -  58 - PC5 - A13               -                               DIO //
// 33     -  57 - PC4 - A12               -                               DIO //
// 34     -  56 - PC3 - A11               -                               DIO //
// 35     -  55 - PC2 - A10               -                               DIO //
// 36     -  54 - PC1 - A9                -                               DIO //
// 37     -  53 - PC0 - A8                -                               DIO //
// 38     -  50 - PD7 - T0                -                               DIO //
// 39     -  70 - PG2 - ALE               -                               DIO //
// 40     -  52 - PG1 - RD                -                               DIO //
// 41     -  51 - PG0 - WR                -                               DIO //
// 42     -  42 - PL7 -                   -                               DIO //
// 43     -  41 - PL6 -                   -                               DIO //
// 44     -  40 - PL5 - OC5C              - 3 Color led Red               PWM //
// 45     -  39 - PL4 - OC5B              - 3 Color led Green             PWM //
// 46     -  38 - PL3 - OC5A              - 3 Color led Blue              PWM //
// 47     -  37 - PL2 - T5                -                               DIO //
// 48     -  36 - PL1 - ICP5              -                               DIO //
// 49     -  35 - PL0 - ICP4              - SDcard Chip Select green      DIO //
// 50     -  22 - PB3 - MISO/PCINT3       - Lan ENC28J60 / SDcard orange  SPI //
// 51     -  21 - PB2 - MOSI/PCINT2       - Lan ENC28J60 / SDcard yellow  SPI //
// 52     -  20 - PB1 - SCK/PCINT1        - Lan ENC28J60 / SDcard blue    SPI //
// 53     -  19 - PB1 - SS/PCINT0         - ENC28J60 Chip Select green    SPI //
// GND    -     - GND - GND               -                               GND //
// GND    -     - GND - GND               -                               GND //
////////////////////////////////////////////////////////////////////////////////




////////////////////////////////////////////////////////////////////////////////
// EEPROM MEMORY MAP:                                                         //
// Start End  Number Description                                              //
// 0000  0000      1   Never use this memory location to be AVR compatible    //
// 0001  0001      1 WATER propWaterProg program 1=off 2=on 3=auto     RELAY1 //
// 0002  0002      1   If capac1 reaches this propWaterON*10 then set  RELAY1 //
// 0003  0003      1   Number seconds*10 propWaterSecs water on        RELAY1 //
// 0004  0004      1 GROEILED1 propLED1Prog program 1=off 2=on 3=auto  RELAY2 //
// 0005  0005      1   Number of propLED1hours around noon groeiled1   RELAY2 //
// 0006  0006      1 VERWARMING propHeatProg program 1=off 2=on 3=auto RELAY3 //
// 0007  0007      1   propHeatON/10 (0-25,5) aanschakeltemperatuur    RELAY3 //
// 0008  0008      1   propHeatOFF/10 (0-25,5) uitschakeltemperatuur   RELAY3 //
// 0009  0009      1 GROEILED2 propLED2prog program 1=off 2=on 3=auto  RELAY4 //
// 0010  0010      1   Number of propLED2hours around noon groeiled2   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  //
////////////////////////////////////////////////////////////////////////////////


/*
void loop() { //KEEP ON RUNNING THIS LOOP FOREVER ******************************
  checkRS232();                //Check if anything has been passed through RS232
}//End of void loop() ------------------------ KEEP ON RUNNING THIS LOOP FOREVER


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 (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 (" ");                         //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 checkRS232() {            //Check if anything has been passed through RS232
  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 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

    //}//End of switch (byteReceived)
  }//End of serial available
} //Exit checkRS232 ------------------------------------------------------------



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





void testLAN(void) { //Obtain an IP-address by DHCP and show on monitor ********
  Serial.println("");                          //Original author: Andrew Lindsay
  Serial.println("TEST LAN ******************");
  Serial.print("MAC: ");
  for (byte i = 0; i < 6; ++i) {
    Serial.print(mymac[i], HEX);
    if (i < 5)
      Serial.print(':');
  }
  Serial.println();
  
  if (ether.begin(sizeof Ethernet::buffer, mymac) == 0) 
    Serial.println(F("Failed to access Ethernet controller"));

  Serial.println(F("Setting up DHCP"));
  if (!ether.dhcpSetup())
    Serial.println(F("DHCP failed"));
  
  ether.printIp("My IP: ", ether.myip);
  ether.printIp("Netmask: ", ether.netmask);
  ether.printIp("GW IP: ", ether.gwip);
  ether.printIp("DNS IP: ", ether.dnsip);
} //Exit testLAN ---------------------------------------------------------------





void testSdCard(void) { //Contact SD card and show all info on monitor *********
  //This routine is honestly stolen from Limor Fried and modified by Tom Igoe
  Serial.print("\nInitializing SD card...");
  if (!card.init(SPI_HALF_SPEED, chipSelect)) {  //We'll use the initialization code from the utility libraries  // since we're just testing if the card is working!
    Serial.println("initialization failed. Things to check:");
    Serial.println("* is a card inserted?");
    Serial.println("* is your wiring correct?");
    Serial.println("* did you change the chipSelect pin to match your shield or module?");
    while (1);
  } else {
    Serial.println("Wiring is correct and a card is present.");
  }

  // print the type of card
  Serial.println();
  Serial.print("Card type:         ");
  switch (card.type()) {
    case SD_CARD_TYPE_SD1:
      Serial.println("SD1");
      break;
    case SD_CARD_TYPE_SD2:
      Serial.println("SD2");
      break;
    case SD_CARD_TYPE_SDHC:
      Serial.println("SDHC");
      break;
    default:
      Serial.println("Unknown");
  }

  // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
  if (!volume.init(card)) {
    Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
    while (1);
  }

  Serial.print("Clusters:          ");
  Serial.println(volume.clusterCount());
  Serial.print("Blocks x Cluster:  ");
  Serial.println(volume.blocksPerCluster());

  Serial.print("Total Blocks:      ");
  Serial.println(volume.blocksPerCluster() * volume.clusterCount());
  Serial.println();

  // print the type and size of the first FAT-type volume
  uint32_t volumesize;
  Serial.print("Volume type is:    FAT");
  Serial.println(volume.fatType(), DEC);

  volumesize = volume.blocksPerCluster();    // clusters are collections of blocks
  volumesize *= volume.clusterCount();       // we'll have a lot of clusters
  volumesize /= 2;                           // SD card blocks are always 512 bytes (2 blocks are 1KB)
  Serial.print("Volume size (Kb):  ");
  Serial.println(volumesize);
  Serial.print("Volume size (Mb):  ");
  volumesize /= 1024;
  Serial.println(volumesize);
  Serial.print("Volume size (Gb):  ");
  Serial.println((float)volumesize / 1024.0);

  Serial.println("\nFiles found on the card (name, date and size in bytes): ");
  root.openRoot(volume);
  root.ls(LS_R | LS_DATE | LS_SIZE);         //List all files with date and size
} //Exit testSdCard ------------------------------------------------------------




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