////////////////////////////////////////////////////////////////////////////////
// Name:       ESP01-1                                                        //
// Platform:   Arduino Mega2560                                               //
// Created by: HARB, May 2018, GPL copyrights                                 //
// http://robotigs.com/robotigs/includes/parts_header.php?idpart=238          //
// Connect ESP-01 to your Arduino:                                            //
// Yellow = Arduino RX1 = ESP-01 TX                                           //
// Blue   = Arduino TX1 = 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 *****************************************************
// Define precompiler variables, constants -------------------------------------
//int bSize = 20; 

// Define PINS -----------------------------------------------------------------
//End of pin declarations

//Define the needed header files for the precompiler, no charge if not used ----
//#include <stdlib.h>
//#include <string.h>                                                             
//#include <stdio.h>  
//#include <wifi.h> //Installed default https://www.arduino.cc/en/Reference/WiFi
// but communicates to a Wifishield through the SPI bus.

//#include <ESP8266WiFi.h>

//END OF PRECOMPILER OPTIONS ---------------------------------------------------


//DECLARE VARIABLES ************************************************************
bool ledBinVal = LOW;       //You can choose HIGH-on or LOW-off as startposition
String inStri = "No answer received";                       //Set receive string
String striLine = "";



char RecChar[15];                         //Definfe a buffrer for readBytesUntil
char Buffer[20];  // Serial buffer
char Command[5];    // Arbitrary Value for command size Up to 5
char Data[15];       // ditto for data size
int ByteCount;
//END OF DECLARE VARIABLES -----------------------------------------------------



void setup() { //Setup runs once ***********************************************
  pinMode(LED_BUILTIN, OUTPUT);          //Arduino boards contain an onboard LED
  Serial.begin(9600);   //Nothing more needed for the Serial Monitor to function
  Serial1.begin(115200);//Nothing more needed for the Serial Monitor to function
  Serial1.setTimeout(1000);        //Max wait in ms before returning as an error
  Test1();                                   //AT system test & AT+GMR version
  //Test2();                                          //Set mode and connect to AP
  //Test3();                                           //Test modes of the ESP01
  Serial.println("Test done");
}//--(end setup )---------------------------------------------------------------



void loop() { //KEEP ON RUNNING THIS LOOP FOREVER ******************************
  toggle_ledBin();                  //Toggles the default on-board LED on or off
  delay(1000);                             //You can test your own patience here
} //End of void loop()                       //KEEP ON RUNNING THIS LOOP FOREVER
//345678911234567892123456789312345678941234567895123456789612345678971234567898


void readESP01(){ //Receives data from the ESP01 Wifi module ******************
  inStri = "";                                    //Reset string to be received
  delay(500);                             //You can test your own patience here
  //terminator : the character to search for (char)
  //Meaning it should be just 1 byte, so basically this function is not fit
  //inStri = Serial1.readStringUntil("OK");          //Read incoming characters

  while (Serial1.available()) {
    striLine = Serial1.readStringUntil('\n');                     //Read a line
    inStri = inStri + striLine;
    delay(500);                           //You can test your own patience here
  }
  delay(100);                            //You can test your own patience here
} //End of readESP01 Receives data from the ESP01 Wifi module -----------------




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



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");                                             //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 connect to AP ----------------------------------



////////////////////////////////////////////////////////////////////////////////
// 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  -                         TWI //
// SDA    -  27 - PC4 -18/A4- ADC4/SDA/PCINT12  -                         TWI //
// AREF   -  31 - REF -     - AREF              -                         REF //
// GND    -  32 - GND -     - GND               -                         GND //
// 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            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 - ESP-01                  INT //
// 19 RX1 -   4 - PD2 -   2 - PCINT18/INT0      - ESP-01                  INT //
// 20 SDA -   3 - PD1 -   1 - PCINT17/TXD       -                         SDA //
// 21 SCL -   2 - PD0 -   0 - PCINT16/RCD       -                         SCL //
//                                                                            //
// 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     -                         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     -  ?? - PL2?-     - ?                 - DHT22 communication     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 //
////////////////////////////////////////////////////////////////////////////////
//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 Test3(void) { //Test modes of the ESP01 ***********************************
  Serial.println("Start test3 ***********************************************");
  Serial.println(" ");                                        //Print empty line

  //Serial.println("AT+CWDHCP - Enable/Disable DHCP **");
  //Serial1.println("AT+CWDHCP=1,0");              //Set as station, enable DHCP
  //readESP01input(1);                             //Receive data from the ESP01
  //Serial.println(" ");                                      //Print empty line
  
  Serial.println("Print IP address **");
  Serial1.println("AT+CIFSR");                           //Show IP address ESP01
  readESP01input(1000,1);             //Receive data from the ESP01 (wait, slow)
  Serial.println(" ");                                        //Print empty line
  
  Serial.println("Print MAC address **");
  Serial1.println("AT+CIPSTAMAC?");                     //Show MAC address ESP01
  readESP01input(1);                               //Receive data from the ESP01
  Serial.println(" ");                                        //Print empty line
  
  Serial.println("Configure as access point host **");
  Serial1.println("AT+CWMODE=3");                    //Configure as access point
  readESP01input(1);                               //Receive data from the ESP01
  Serial.println(" ");                                        //Print empty line
 
  Serial.println("Lists valid modes **");
  Serial1.println("AT+CWMODE=?");                             //List valid modes
  readESP01input(1);                      //Receive data from the Serial Monitor
  Serial.println(" ");                                        //Print empty line
 
  Serial.println("AT+RST Restart ESP8266 **");                     //ANSWERS: OK
  Serial1.println("AT+RST");               //Reset ESP8266 and show startup data
  readESP01input(10000,100);        //Receive data from the ESP8266 (wait, slow)
  Serial.println(" ");                                        //Print empty line

  Serial.println("AT+RESTORE Restore **");                         //ANSWERS: OK
  Serial1.println("AT+RESTORE");                            //Soft reset ESP8266
  readESP01input(10000,100);        //Receive data from the ESP8266 (wait, slow)
  Serial.println(" ");                                        //Print empty line

  Serial.println("AT+CIOBAUD? **");                             //ANSWERS: ERROR
  Serial1.println("AT+CIOBAUD?");                        //Show current byterate
  readESP01input(1000,1);           //Receive data from the ESP8266 (wait, slow)
  Serial.println(" ");                                        //Print empty line

  Serial.println("AT+CWMODE? **");                          //ANSWERS: +CWMODE:3
  Serial1.println("AT+CWMODE?");                       //Query current Wifi mode
  readESP01input(1000,1);           //Receive data from the ESP8266 (wait, slow)
  Serial.println(" ");                                        //Print empty line
} //End of Test3   Test modes of the ESP01 -------------------------------------
*/



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