//RTC
#include "RTClib.h"
RTC_DS1307 rtc;

//MPU
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
Adafruit_MPU6050 mpu;

//Thermistor
const float BETA = 3950; // should match the Beta Coefficient of the thermistor

//SD
#include <SD.h>
#define CS_PIN 10
File root;


void setup () {
  Serial.begin(9600);
  rtc_setup();
  // mpu_setup();
  sdcard_setup();

}

void loop () {

//RTC
  DateTime now = rtc.now();
  int hour = now.hour();
  int minute = now.minute();
  int second = now.second();

//MPU
  /* Get new sensor events with the readings */
  sensors_event_t a, g, temp;
  mpu.getEvent(&a, &g, &temp);

  float X_acc = a.acceleration.x;
  float Y_acc = a.acceleration.y;
  float Z_acc = a.acceleration.z;
  float temp_1 = temp.temperature;

//Thermistor
  int temp_analog = analogRead(A0);
  float temp_2 = 1 / (log(1 / (1023. / temp_analog - 1)) / BETA + 1.0 / 298.15) - 273.15;

//print
  Serial.print(hour);
  Serial.print(",");
  Serial.print(minute);
  Serial.print(",");
  Serial.print(second);
  Serial.print(",");
  Serial.print(millis());
  Serial.print(",");
  Serial.print(X_acc);
  Serial.print(",");
  Serial.print(Y_acc);
  Serial.print(",");
  Serial.print(Z_acc);
  Serial.print(",");
  Serial.print(temp_1);
  Serial.print(",");
  Serial.print(temp_2);
  Serial.println("");

  delay(100);
}

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

void mpu_setup(){
  // Try to initialize!
  if (!mpu.begin(0x69)) {
    Serial.println("Couldn't find MPU6050");
    while (1) {
      delay(10);
    }
  }
  Serial.println("MPU6050 Found!");
}

void sdcard_setup(){
  Serial.print("Initializing SD card... ");

  if (!SD.begin(CS_PIN)) {
    Serial.println("Card initialization failed!");
    while (true);
  }

  Serial.println("initialization done.");

  Serial.println("Files in the card:");
  root = SD.open("/");
  printDirectory(root, 0);
  Serial.println("");  
}

void printDirectory(File dir, int numTabs) {
  while (true) {

    File entry =  dir.openNextFile();
    if (! entry) {
      // no more files
      break;
    }
    for (uint8_t i = 0; i < numTabs; i++) {
      Serial.print('\t');
    }
    Serial.print(entry.name());
    if (entry.isDirectory()) {
      Serial.println("/");
      printDirectory(entry, numTabs + 1);
    } else {
      // files have sizes, directories do not
      Serial.print("\t\t");
      Serial.println(entry.size(), DEC);
    }
    entry.close();
  }
}
GND5VSDASCLSQWRTCDS1307+