/*
  Demo 2 – Datalogging at regular intervals
  For Instructable: Arduino Data Logging Shield With Real Time Clock Timestamp ... and Telemetry, Sensor Network
  Link: https://www.instructables.com/Arduino-Data-Logging-Shield-With-Real-Time-Clock-T/
  Youtube video demonstration: https://youtu.be/NfFThtyfbRM
  By JD_K April 2023

  Uses ARduino, DS1307, microSD card reader module, thermistor, etc.
*/

#include <Wire.h> // the SD1307 uses I2C
#include "uRTCLib.h"
uRTCLib rtc;

#include <SPI.h>
#include <SD.h>
int CSpin = 9;
int recordingLEDPin = 13; // this will go HIGH when the datalogger is recording (so don't unplug it then)

int tempPin = 0; // Analog pin for the thermistor

unsigned long prevMillis; // an unsigned long can count to 4,294,967,295, which is enough miliseconds to last almost 50 days then it rolls over to zero again
const unsigned long measurementInterval = 5000; // interval in milliseconds between measurements

void setup() {
  Serial.begin(9600);
  Serial.println("Ready");

  // *** uRTCLib code
  URTCLIB_WIRE.begin();
  //  rtc.set(0, 26, 1, 1, 7, 2, 21);
  //  RTCLib::set(byte second, byte minute, byte hour, byte dayOfWeek, byte dayOfMonth, byte month, byte year)

  pinMode(recordingLEDPin, OUTPUT);

  // *** Initiallizing the SD card Reader
  Serial.println("Initializing Card");
  digitalWrite(recordingLEDPin, HIGH);
  pinMode(CSpin, OUTPUT);

  //Check if card is ready
  if (!SD.begin(CSpin))
  {
    Serial.println("Card Failed");
    digitalWrite(recordingLEDPin, LOW);
    return; //this command will end the whole sketch, and is used because if the SD card reader does not initialize there is no need to go any further
  }
  Serial.println("Card Ready");

  //Write Log File Header - use a short file name otherwise it may not work
  File logFile = SD.open("Data.csv", FILE_WRITE);
  if (logFile)
  {
    logFile.println(", , , , ,"); // Just a leading blank line, in case there was previous data
    logFile.println("Month,Day,Hour,Minutes,Seconds,Celcius"); // Headers for the columns of data
    logFile.close();
    Serial.println("Month,Day,Hour,Minutes,Seconds,Celcius");
    digitalWrite(recordingLEDPin, LOW);
  }
  else
  {
    Serial.println("Could not open command file to print header.");
    digitalWrite(recordingLEDPin, LOW);
    return;
  }
  // *** End the SD card reader code in the setup

}

void loop() {

  if ((millis() - prevMillis > measurementInterval) || (millis() < prevMillis)) {
    prevMillis = millis();

    // Coding from Elegoo Complete Starter Kit
    int tempReading = analogRead(tempPin);
    double tempK = log(10000.0 * ((1024.0 / tempReading - 1)));
    tempK = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * tempK * tempK )) * tempK );       //  Temp Kelvin
    float tempC = tempK - 273.15;            // Convert Kelvin to Celcius

    //Update time and date from RTC:
    rtc.refresh();

    //Prepare a string in CSV format so that it can then be uplaoded to the log file
    digitalWrite(recordingLEDPin, HIGH);
    String dataString = String(rtc.month()) + "," + String(rtc.day()) + "," + String(rtc.hour()) + "," + String(rtc.minute()) + "," + String(rtc.second()) + "," + String(tempC);

    //Open a file to write to. Note only one file can be open at a time
    Serial.println("Recording...");
    File logFile = SD.open("Data.csv", FILE_WRITE); //this will open a new file if this does not exist already, or open the existing file of the same name
    if (logFile)
    {
      logFile.println(dataString);
      logFile.close();
      digitalWrite(recordingLEDPin, LOW);
      Serial.println(dataString);
    }
    else
    {
      Serial.println("Could not open log file to record date");
      digitalWrite(recordingLEDPin, LOW);
    }
    Serial.flush(); //empty the serial monitor buffer
  }

} // End of the Loop
