
#include <SPI.h>
#include <SD.h>
//pin SCK  -> 13
//pin MOSI ->  11
//pin MISO ->  12
const int ChipSelect = 4; // pin 4 UNO --> pin CS (chip select) SD card module


void setup()
{
  Serial.begin(9600);

  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.print("SD card initialized...");// see if the card is present and can be initialized:
  
  if (!SD.begin(ChipSelect)) {
    Serial.println("Card failed to read,or ..");
    // don't do anything more:
    while (1);
  }
  Serial.println("Reading card complete.");
}

void loop()
{
  File dataFail = SD.open("tempLog.txt", FILE_WRITE);
  if (dataFail) {
    dataFail.println(getTemp(),1);
    dataFail.close();
    // print to the serial port too:
    Serial.println(getTemp(),1);
    delay(10000); // 10 seconds delay
  }
  // if failed:
  else {
    Serial.println("failed to read tempLog.txt");
  }
    
}

double getTemp() // reference from https://www.engineersgallery.com/arduino-internal-temperature-sensor/
{
  unsigned int wADC;
  double t;

  // The internal temperature has to be used
  // with the internal reference of 1.1V.
  // Channel 8 can not be selected with
  // the analogRead function yet.

  // Set the internal reference and mux.
  ADMUX = (_BV(REFS1) | _BV(REFS0) | _BV(MUX3));
  ADCSRA |= _BV(ADEN);  // enable the ADC

  delay(20);            // wait for voltages to become stable.

  ADCSRA |= _BV(ADSC);  // Start the ADC

  // Detect end-of-conversion
  while (bit_is_set(ADCSRA,ADSC));

  // Reading register "ADCW" takes care of how to read ADCL and ADCH.
  wADC = ADCW;

  // The offset of 324.31 could be wrong. It is just an indication.
  t = (wADC - 324.31 ) / 1.22;

  // The returned temperature is in degrees Celcius.
  return (t);
}
