////////////////////////////////////////////////////////////////////////////////
// Name:       Gateway03.ino                                                  //
// Platform:   Arduino Mega 2650 R3                                           //
// Created by: HARB rboek2@gmail.com October 2020 GPL copyrights              //
// http://robotigs.nl/robots/includes/bots.php?idbot=32                       //
// http://tmrh20.github.io/RF24/GettingStarted_8ino-example.html              //
////////////////////////////////////////////////////////////////////////////////
// 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:                               //
//                                                                            //
// For communications and statistics are mounted:                             //
// - Standard Serial Monitor output                                           //
//           http://robotigs.nl/robotigs/includes/parts_header.php?idpart=43  //
// - Lan ENC28J60 module                                                      //
//           http://robotigs.nl/robotigs/includes/parts_header.php?idpart=313 //
// - LoRa NRF24L01+ module                                                    //
//           http://robotigs.nl/robotigs/includes/parts_header.php?idpart=344 //
////////////////////////////////////////////////////////////////////////////////


  //Define the needed header files for the precompiler, no charge if not used --
  #include <SPI.h>      //Serial Peripheral Interface requiered by software LORA
                       // http://robotigs.nl/robots/includes/parts.php?idpart=28
  #include <RF24.h>                  //TMRH20 https://github.com/nRF24/RF24 LORA
                      // http://robotigs.nl/robots/includes/parts.php?idpart=344
  #include <printf.h>             //Needed to send to monitor radio.printDetails
  #include <UIPEthernet.h> //https://github.com/UIPEthernet/UIPEthernet ENC28J60
                      // http://robotigs.nl/robots/includes/parts.php?idpart=313
  #include <PubSubClient.h>          // https://pubsubclient.knolleary.net/ MQTT
                      // http://robotigs.nl/robots/includes/parts.php?idpart=114

  //Define PINS ----------------------------------------------------------------
  #define CE_PIN        8          //CE (Chip Enable) is an active-HIGH pin LORA
  #define CSN_PIN       7          //CSN (Chip Select Not) is an active-LOW LORA
  //#define chipSelect  7      //SPI Chip select LAN pin mut be 53, so LORA is 7
  #define ledRedPin    44         //3 Colour LED, which PWM pin connects RED LED
  #define ledGrePin    45       //3 Colour LED, which PWM pin connects GREEN LED
  #define ledBluPin    46        //3 Colour LED, which PWM pin connects BLUE LED
  #define buzActPin     2          //Define DIO output pin connects ACTIV BUZZER
   //#define SpiMISO = 50             //PB3 -- MISO/PCINT3  SPI pin LAN ENC28J60
   //#define SpiMOSI = 51              //PB2 -- MOSI/PCINT2 SPI pin LAN ENC28J60
   //#define SpiSCK  = 52               //PB1 -- SCK/PCINT1 SPI pin LAN ENC28J60
   //#define SpiSS   = 53                //PB0 -- CS/PCINT0 SPI pin LAN ENC28J60


  //Define EEPROM variables ----------------------------------------------------
  //Define DATABASE VARIABLES --------------------------------------------------
  //Define variables -----------------------------------------------------------
  int           ledOnBoardVal  =   LOW;     //HIGH-on or LOW-off for LED_BUILTIN
  const byte    thisSlaveAddress[5] = {'R','x','A','A','A'}; //?????????????????
  char          dataReceived[10];    //This must match dataToSend in the TX MQTT
  bool          newData = false;
  char          tmp;                                      //Can be used anywhere
  unsigned long countOk, countNok;  //Counters for long term tests on stabillity
  unsigned long readCounter  = 1; //Periodic if counted down to zero MAIN TIMING
  unsigned long counterReset = 1000000;//Set counter if down to zero MAIN TIMING

  //User configuration RF24 radio ----------------------------------------------
  bool          radioNumber    = 1;        //Set radio number 1=Ping 0=Pong LORA
  bool          role           = 0;         //Sending=0 or receiving=1 role LORA
  byte          addresses[][6] = {"1Node","2Node"};                       //LORA
  bool          test           = false;                                   //LORA
  char          answer[32]     = {0};          //Needed for string receival LORA

  String        tmpStr         = "";

  char          temp[5]        = "-199";      //Needed for string retreival LORA
  float         tempPrev       = 0;        //Needed to not send double data LORA
  float         temperatuur    = 0;        //Needed to not send double data LORA

  char          humi[4]        = "199";       //Needed for string retreival LORA
  float         humiPrev       = 0;        //Needed to not send double data LORA
  float         humidity       = 0;        //Needed to not send double data LORA

  char          gas1[5]        = "199";       //Needed for string retreival LORA
  float         gas1Prev       = 0;        //Needed to not send double data LORA
  float         gasMQ          = 0;        //Needed to not send double data LORA

  byte          mac[] = {0x00,0x01,0x02,0x03,0x04,0x17};              //ETHERNET


  char          Celcius[8]  = "99.9";      //Benodigd om data te publiceren MQTT
  String        opdracht    = "aan";        //Benodigd om data te ontvangen MQTT
  boolean       r;                                                        //MQTT
  //Initialize OBJECTS ---------------------------------------------------------
  EthernetClient ethClient;                                           //ETHERNET
  PubSubClient mqttClient(ethClient);                                     //MQTT
  RF24 radio(CE_PIN, CSN_PIN);                 //CE=10 CSN=9 Speed settings LORA
//END OF PRECOMPILER OPTIONS ---------------------------------------------------



void setup() { //Setup runs once ***********************************************
  Serial.begin(115200);
  Serial.println("LoRa Gateway setup");
  Serial.println("");

  pinMode(LED_BUILTIN, OUTPUT);  //Arduino boards contain an onboard LED_BUILTIN
  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
  pinMode(buzActPin, OUTPUT);                 //Set this pin as output to BUZZER

  //Start objects --------------------------------------------------------------
  startEthernet();              //Start client and get network settings via DHCP
  startMQTT();                          //Start client and and set callback MQTT
  startLoRa();                              //Start radio and make settings LoRa

  //Test hardware and software -------------------------------------------------
  Serial.println("Start Tests");                           //Show the user RS232
  printf_begin();        //Needed to print the radio.printDetails() to a monitor
  radio.printDetails();               //Set of data about the transceiver status
  test_LEDs();            //PWM fade in and fade out for all 4 LEDs on board LED
  Serial.println("Setup completed");     //Show the user the setup is done RS232
  beep(1);                        //Create a test beep with KY-012 active BUZZER
  Serial.println("");
} //End of setup ---------------------------------------------------------------






void loop() { //KEEP ON RUNNING THIS LOOP FOREVER  *****************************
  mqttClient.loop();            //Put at the top of the loop so its often called
  readLoRa();                      //Read LoRa sensors at counted intervals only
} //End of void loop() ----------------------- KEEP ON RUNNING THIS LOOP FOREVER






void readLoRa() { //Read LoRa sensors at timed intervals only ******************
  if (readCounter == 0){       //Only perform measurements if counted down TIMER
    Serial.println("  Counter=0");
    readCounter = counterReset;                        //RESET the counter TIMER
    digitalWrite(ledGrePin, HIGH);          //Green HIGH=on, LOW=off activityLED
    pingout();                   //Ping sends out timestamp and waits for return

    if (temperatuur != tempPrev) {
      Serial.print("=>publiceert");
      if (!mqttClient.publish("/2802ZS9/kas/sensors/DHT22/celcius/", temp)) {
        Serial.println("geen MQTT data verzonden");        //Show activity RS232
        reconnect();
        r = mqttClient.publish("/2802ZS9/kas/sensors/DHT22/celcius/", Celcius);
      }
    tempPrev = temperatuur;
    }

    if (humidity != humiPrev) {
      Serial.print("=>publiceert");
      if (!mqttClient.publish("/2802ZS9/kas/sensors/DHT22/luchtvo/", humi)) {
        Serial.println("geen MQTT data verzonden");        //Show activity RS232
        reconnect();
        r = mqttClient.publish("/2802ZS9/kas/sensors/DHT22/luchtvo/", humi);
      }
    humiPrev = humidity;
    }

    if (gasMQ != gas1Prev) {
      Serial.print("=>publiceert");
      if (!mqttClient.publish("/2802ZS9/kas/sensors/MQ/gas1/", gas1)) {
        Serial.println("geen MQTT data verzonden");        //Show activity RS232
        reconnect();
        r = mqttClient.publish("/2802ZS9/kas/sensors/MQ/gas1/", gas1);
        //gas1Prev = gas1; 
      }
    gas1Prev = gasMQ; 
    }
    digitalWrite(ledGrePin, LOW);            //Blue HIGH=on, LOW=off activityLED
    Serial.println("=Done");
    Serial.println("");
  }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 pingout(void) { //Ping sends out timestamp and waits for return LORA ******
  radio.stopListening();                   //First stop listening so we can talk
  Serial.println("*** Now sending");            //Show the start of the sequence
  unsigned long start_time = micros();               //Read the time and send it
  if (!radio.write( &start_time, sizeof(start_time) )){
    Serial.println("    Error radio.write failed");                      //Error
    radio.printDetails();
  } //End of if (!radio.write( &start_time, sizeof(unsigned long) ))
  
  radio.startListening();                           //Start listening for answer
  unsigned long started_waiting_at = micros();        //Start timer microseconds
  boolean timeoutbool = false;         //Indicate if radio is receiving anything

  while (!radio.available()){                   //As long as nothing is received
    if (micros() - started_waiting_at > 200000 ){       //If waited longer 200ms
        timeoutbool = true;               //Then indicate timeout and exit while
        break;                              //Exit waiting in case of a time-out
    } //End of if (micros() - started_waiting_at > 200000 )
  } //End of while (!radio.available())

  if (timeoutbool){                                       //Describe the results
    countNok++;                                               //One more failure
    Serial.println("    Failed, response timed out.");
    if (!mqttClient.publish("/2802ZS9/kas/sensors/MQ/gas1/errors/", "LoRa error kas")) {
      Serial.println("geen MQTT data verzonden");         //Show activity RS232
      reconnect();
      r = mqttClient.publish("/2802ZS9/kas/sensors/MQ/gas1/errors/", "LoRa error kas");
    } //End of if
  }else{
    radio.read(&answer, sizeof(answer));
    countOk++;                               //One more succesfull communication
    temp[0] = answer[0];
    temp[1] = answer[1];
    temp[2] = answer[2];
    temp[3] = answer[3];
    tmpStr = temp;
    temperatuur = (tmpStr.toInt());

    humi[0] = answer[5];
    humi[1] = answer[6];
    humi[2] = answer[7];
    tmpStr = humi;
    humidity = (tmpStr.toInt());
    
    gas1[0] = answer[9];
    gas1[1] = answer[10];
    gas1[2] = answer[11];
    gas1[3] = answer[12];
    tmpStr = gas1;
    gasMQ = (tmpStr.toInt());

    Serial.print("    Answer: [");
    Serial.print(answer);

    Serial.print("]  Temperatuur");
    Serial.print(temp);
    Serial.print(" Luchtvochtigheid");
    Serial.print(humi);
    Serial.print("% ");
    Serial.print(" Gasconcentratie");
    Serial.println(gas1);
  }
  Serial.print("    Succesvol:");
  Serial.print(countOk);
  Serial.print("  Mislukkingen:");
  Serial.print(countNok);
  Serial.print("  Wacht 20 seconden");
} //Exit pingout ---------------------------------------------------------------





void callback(char* topic, byte* payload, unsigned int length) { //MQTT ********
  opdracht = "";
  String onderwerp = String(topic);
  Serial.print("Boodschap ontvangen [");
  Serial.print(onderwerp);
  Serial.print("] ");
  for (int i=0;i<length;i++) {
    opdracht += (char)payload[i];
    Serial.print((char)payload[i]);
  }
  Serial.println(""); 

  if (onderwerp == "/2802ZS9/kas/actuators/verwarming/opdracht/"){
    if (opdracht == "aan"){                                 //1 = VERWARMING AAN
      //progHeater = 1;                        //0=unknown, 1=aan, 2=uit, 3=auto
      //EEPROM.write(1, 1);                           //Write 1 byte into eeprom
      Serial.println("Opdracht: verwarming aan");
    }
    if (opdracht=="uit"){                                   //2 = VERWARMING UIT
      //progHeater = 2;                        //0=unknown, 1=aan, 2=uit, 3=auto
      //EEPROM.write(1, 2);                           //Write 1 byte into eeprom
      Serial.println("Opdracht: verwarming uit");
    }
    if (opdracht=="auto"){                                 //3 = VERWARMING AUTO
      //progHeater = 3;                        //0=unknown, 1=aan, 2=uit, 3=auto
      //EEPROM.write(1, 3);                           //Write 1 byte into eeprom
      Serial.println("Opdracht: verwarming automatisch");
    }
    //setRelay1();                         //Calculate and set relay1 VERWARMING
  }
} //Exit callback --------------------------------------------------------------





void reconnect() { //Loop until we're connected ********************************
  while (!mqttClient.connected()) {
    Serial.println("Attempting MQTT connection...");
    //String clientId = "Dit is niet echt random";   //Create a random client ID
    if (mqttClient.connect("LoRaGateway", "", "")) {
    }else{
      delay(1000);
      Serial.print("failed, rc=");
      Serial.print(mqttClient.state());
      Serial.println(" try again in 5 seconds");    //Wait 5 seconds b4 retrying
      delay(1000);
    }
  }
} //Exit reconnect -------------------------------------------------------------




void startEthernet(void) { //Start client and get network settings via DHCP ****
  Serial.println("Start ethernet");
  Ethernet.begin(mac);
  Serial.print("  LocalIP: ");
  Serial.println(Ethernet.localIP());
  Serial.print("  SubnetMask: ");
  Serial.println(Ethernet.subnetMask());
  Serial.print("  GatewayIP: ");
  Serial.println(Ethernet.gatewayIP());
  Serial.print("  DnsServerIP: ");
  Serial.println(Ethernet.dnsServerIP());
  Serial.println("");
}//Exit startEthernet ----------------------------------------------------------




void startMQTT(void) { //Start client and and set callback MQTT ****************
  Serial.println("Start mqttClient"); //MQTT -----------------------------------
  mqttClient.setServer("192.168.2.24", 1883);                   //1883 9001 MQTT
  mqttClient.setCallback(callback);
  if (mqttClient.connect("LoRaGateway", "", "")) {                    //ClientId
    Serial.println("  Connection established");
  } else {                                                  // connection failed
    Serial.println(" Connection failed ");
    reconnect();                                 // Loop until we're reconnected
  }
  r = mqttClient.subscribe("/2802ZS9/lora/kas/actuators/#");
  Serial.print("  Subscribe ");
  Serial.println(r);
  r = mqttClient.publish("LoRaGateway", "online"); //Voor statistieken op broker
}//Exit startMQTT --------------------------------------------------------------




void startLoRa(void) { //Start radio and make settings LoRa ********************
  radio.begin(); //LORA --------------------------------------------------------
  test = radio.setDataRate(RF24_250KBPS);
  Serial.print("  Radio.setDataRate succeeded: ");
  Serial.println(test);
  Serial.println("");
  radio.setPALevel(RF24_PA_MIN);             //RF24_PA_MAX=default, HIGH LOW MIN
  radio.setRetries(3,5);                                      //Delay=3, count=5
  radio.openWritingPipe(addresses[1]);
  radio.openReadingPipe(1,addresses[0]);
  radio.startListening();                  // Start the radio listening for data
}//Exit startLoRa --------------------------------------------------------------





void test_LEDs(void){ //PWM fade in and fade out for all 4 LEDs on board *******
  byte brillance = 0;            //Brightness of any color, just to test PWM LED
  byte   msWait  = 2;                   //Test your patience during the test LED

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

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

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

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





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





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




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




////////////////////////////////////////////////////////////////////////////////
// PIN ALLOCATIONS TABLE ARDUINO MEGA 2560                                    //
// Board  -Atmel- PIN - Function          - External Connection          FUNC //
//                                                                            //
// CONNECTIONS RAILS RIGHT TOP: DIGITAL PWM<~> ****************************** //
// SCL    -  43 - PD0 - SCL/INT0          - Clock DS1307                  TWI //
// SDA    -  44 - PD1 - SDA/INT1          - Clock DS1307                  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         - Buzzer activ              Wit 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              -                               RX2 //
// 18 TX1 -  46 - PD3 - TXD1/INT3         -                               INT //
// 19 RX1 -  45 - PD2 - RXD1/INT2         -                               INT //
// 20 SDA -  44 - PD1 - SDA/INT1          -                               TWI //
// 21 SCL -  43 - PD0 - SCL/INT0          -                               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          -                               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              -                               DIO //
// 50     -  22 - PB3 - MISO/PCINT3       - Lan ENC28J60                  SPI //
// 51     -  21 - PB2 - MOSI/PCINT2       - Lan ENC28J60                  SPI //
// 52     -  20 - PB1 - SCK/PCINT1        - Lan ENC28J60                  SPI //
// 53     -  19 - PB1 - SS/PCINT0         - Lan ENC28J60                  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  //
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
// 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 LoRa groen  BUILT_IN SPI //
// 12    -  18 - PB4 -  12 - MISO/PCINT4       - MISO LoRa paars          SPI //
// ~11   -  17 - PB3 -  11 - MOSI/OC2A/PCINT3  - MOSI Lora blauw      PWM SPI //
// ~10   -  16 - PB2 -  10 - SS/OC1B/PCINT2    - CE LoRa geel         PWM SPI //
// ~9    -  15 - PB1 -   9 - OC1A/PCINT1       - CSN LoRa oranje          PWM //
// 8     -  14 - PB0 -   8 - PCINT0/CLK0/ICP1  -                          DIO //
//                                                                            //
// CONNECTIONS RAILS TOP RIGHT: DIGITAL PWM<~> ****************************** //
// 7     -  13 - PD7 -   7 - PCINT23/AIN1      -                          DIO //
// ~6    -  12 - PD6 -   6 - PCINT22/OCA0/AIN0 - Blauwe led               PWM //
// ~5    -  11 - PD5 -   5 - PCINT21/OC0B/T1   - Groene led               PWM //
// 4     -   6 - PD4 -   4 - PCINT20/XCK/T0    - Buzzer                   INT //
// ~3    -   5 - PD3 -   3 - PCINT19/OC2B/INT1 - Rode led                 PWM //
// ~2    -   4 - PD2 -   2 - PCINT18/INT0      -                          INT //
// TX->1 -   3 - PD1 -   1 - PCINT17/TXD       - Serial monitor           TXD //
// RX<-0 -   2 - PD0 -   0 - PCINT16/RCD       - Serial Monitor           RCD //
//                                                                            //
// CONNECTIONS RAILS BOTTOM LEFT: POWER ************************************* //
// 5V    -   7 - VCC -     - VCC               -                          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  -                          TWI //
// A5    -  28 - PC5 -A5/19- ADC5/SCL/PCINT13  -                          TWI //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////