//GROUP 1
//LAB 8 LAB EXERCISE

#include <DHT.h>;
#include "RTClib.h"
#include <SD.h>

#define DHTPIN 2
#define DHTTYPE DHT22             
DHT dht(DHTPIN, DHTTYPE);         
RTC_DS1307 rtc;
#define CS_PIN 10

float temp;
float hum;
int hour;
File root;

void setup()
{
  Serial.begin(115200);

  dht.begin();                                                    

  if (! rtc.begin()) {                                            
    Serial.println("Couldn't find RTC");
    Serial.flush();
    abort();
  }

  Serial.print("Initializing SD card... ");                       
  if (!SD.begin(CS_PIN)) {
    Serial.println("Card initialization failed!");
    while (true);
  }
  Serial.println("initialization done.");     
  Serial.println("Beginning Temperature Data Logger...");
  Serial.println("temp_log.txt content:");

  File writeFile = SD.open("temp_log.txt", FILE_WRITE);         
  writeFile.println("-- Temperature -- Humidity -- Time -- Date --");
  writeFile.close();

}


void loop()
{
  DateTime now = rtc.now();
  temp = dht.readTemperature();
  hum = dht.readHumidity();

  File writeFile = SD.open("temp_log.txt", FILE_WRITE);            
  writeFile.print("-- ");
  writeFile.print(temp);
  writeFile.print(" C      --");
  writeFile.print("    ");
  writeFile.print("-- ");
  writeFile.print(hum);
  writeFile.print(" %        --");
  writeFile.print("    ");
  if (now.hour() > 12) {
    writeFile.print(now.hour() - 12);
  } else {
    writeFile.print(now.hour(), DEC);
  }
  writeFile.print(':');
  writeFile.print(now.minute(), DEC);
  writeFile.print(':');
  writeFile.print(now.second(), DEC);
  writeFile.print("    --      ");
  writeFile.print(now.month(), DEC);
  writeFile.print('/');
  writeFile.print(now.day(), DEC);
  writeFile.print('/');
  writeFile.print(now.year(), DEC);
  writeFile.println("     --");
  writeFile.close();


  Serial.println();
  File textFile = SD.open("temp_log.txt");                        
  if (textFile) {
    while (textFile.available()) {
      Serial.write(textFile.read());
    }
    textFile.close();
  } else {
    Serial.println("error opening temp_log.txt!");
  }
  delay(5000);
}
GND5VSDASCLSQWRTCDS1307+