////////////////////////////////////////////////////////////////////////////////
// Name:       SDcard-check                                                   //
// Platform:   Arduino UNO R3                                                 //
// Created by: HARB rboek2@gmail.com Januar 2020 GPL copyrights               //
// http://robotigs.com/robotigs/includes/parts_header.php?idpart=116          //
// SD card basic tests.  This example shows how to create and destroy a       //
// SD card file. Use serial monitor to see test results.                      //
// Thanks to:  2010 by David A. Mellis  modified 2012 by Tom Igoe             //
////////////////////////////////////////////////////////////////////////////////



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



  //Define PINS ----------------------------------------------------------------
  #define ledBluPin     3        //3 Colour LED, which PWM pin connects BLUE LED
  #define ledGrePin     5       //3 Colour LED, which PWM pin connects GREEN LED
  #define ledRedPin     6         //3 Colour LED, which PWM pin connects RED LED
  #define SDssPin      10    //SPI Chip select pin at the SD CARD UNO=10 2560=53
  /*The circuit: SD card must be attached to SPI bus as follows:
  ** MOSI - pin 11
  ** MISO - pin 12
  ** CLK - pin 13
  ** CS - pin 10 at Uno */



  //Define EEPROM variables ----------------------------------------------------
  //Define DATABASE VARIABLES --------------------------------------------------      
  //Define variables -----------------------------------------------------------



  //Initialize OBJECTS ---------------------------------------------------------
  File myFile;                      //Creates a file object in memory for SDcard
//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
  pinMode(LED_BUILTIN, OUTPUT);  //Arduino boards contain an onboard LED_BUILTIN

  //Start objects --------------------------------------------------------------
  //Test hardware and software -------------------------------------------------
  Serial.print("Initializing SD card...");

  if (!SD.begin(10)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  if (SD.exists("datalog.txt")) {
    Serial.println("datalog.txt exists.");
  } else {
    Serial.println("datalog.txt doesn't exist.");
  }

  // open a new file and immediately close it:
  Serial.println("Creating datalog.txt...");
  myFile = SD.open("datalog.txt", FILE_WRITE);
  myFile.close();

  // Check to see if the file exists:
  if (SD.exists("datalog.txt")) {
    Serial.println("datalog.txt exists.");
  } else {
    Serial.println("datalog.txt doesn't exist.");
  }

  // delete the file:
  //Serial.println("Removing example.txt...");
  //SD.remove("example.txt");

  if (SD.exists("datalog.txt")) {
    Serial.println("datalog.txt exists.");
  } else {
    Serial.println("datalog.txt doesn't exist.");
  }
  //test_LEDs();     //PWM fade in and fade out for 3 colorLEDs on board ALL LED
} //End of setup ---------------------------------------------------------------





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 test_LEDs(void){ //PWM fade in and fade out for all 4 LEDs on board *******
  brillance = 0;                 //Brightness of any color, just to test PWM LED

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

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

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


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




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




////////////////////////////////////////////////////////////////////////////////
// EEPROM MEMORY MAP:                                                         //
// Start End  Number Description                                              //
// 0000  0000    1        Never use this memory location to be AVR compatible //
// 0001  0001    1   WERKVERLICHTING hobbyLightProg: 1=off 2=on 3=auto RELAY1 //
// 0002  0002    1     If LDR reaches this kasLightON*10 switch        RELAY1 //
// 0003  0003    1     kasLightSecs*10 werkverlichting on              RELAY1 //
// 0004  0004    1   VERWARMING hobbyHeatProg: 1=off 2=on 3=auto       RELAY2 //
// 0005  0005    1     Celsius hobbyHeatON/10 verwarming switch on     RELAY2 //
// 0006  0006    1     Celsius hobbyHeatOFF/10 verwarming switch off   RELAY2 //
// 0007  0007    1   GROEILED hobbyLedProg: 1=off 2=on 3=auto          RELAY3 //
// 0008  0008    1     Hours kasLedHours around noon to switch on      RELAY3 //
// 0009  0009    1   WATER hobbyWaterProg: 1=off 2=on 3=auto           RELAY4 //
// 0010  0010    1     hobbyWaterSecs*10 to keep watering              RELAY4 //
// 0011  0011    1   AUDIO hobbyAudioProg: 1=off 2=on 3=auto           RELAY5 //
// 0012  0012    1     hobbyAudioMins*10 to keep audio playing         RELAY5 //
////////////////////////////////////////////////////////////////////////////////



////////////////////////////////////////////////////////////////////////////////
// FUSES (can always be altered by using the STK500)                          //
// On-Chip Debug Enabled: off                            (OCDEN=0)            //
// JTAG Interface Enabled: off                           (JTAGEN=0)           //
// Preserve EEPROM mem through the Chip Erase cycle: On  (EESAVE = 0)         //
// Boot Flash section = 2048 words, Boot startaddr=$3800 (BOOTSZ=00)          //
// Boot Reset vector Enabled, default address=$0000      (BOOTSTR=0)          //
// CKOPT fuse (operation dependent of CKSEL fuses        (CKOPT=0)            //
// Brown-out detection level at VCC=2,7V;                (BODLEVEL=0)         //
// Ext. Cr/Res High Freq.; Start-up time: 16K CK + 64 ms (CKSEL=1111 SUT=11)  //
//                                                                            //
// LOCKBITS (are dangerous to change, since they cannot be reset)             //
// Mode 1: No memory lock features enabled                                    //
// Application Protect Mode 1: No lock on SPM and LPM in Application Section  //
// Boot Loader Protect Mode 1: No lock on SPM and LPM in Boot Loader Section  //
////////////////////////////////////////////////////////////////////////////////
//345678911234567892123456789312345678941234567895123456789612345678971234567898