/*************************************************************************************
  This program is SD_test.ino. It is based on the Arduino example sketch ReadWrite,ino.

  SD card read/write

  This example shows how to read and write data to and from an SD card file
  The circuit:
   SD card attached to SPI bus as follows:
 ** MOSI - pin 24 (11 in the original example)
 ** MISO - pin 23 (12 in the original example)
 ** CLK  - pin 25 (13 in the original example)
 ** CS   - pin 4  (also 4 in the original example, for MKRZero SD: SDCARD_SS_PIN)

  created   Nov 2010
  by David A. Mellis
  modified 9 Apr 2012
  by Tom Igoe

  This example code is in the public domain.

*************************************************************************************/

#include <SPI.h>
#include <SD.h>

File myFile;

void setup() 
{
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {}

  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("SD initialization failed!");
    while (1);
  }

  Serial.println("SD initialization done. Now open test.txt");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  myFile = SD.open("test.txt", FILE_WRITE);

  uint32_t millis_start = millis();

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to test.txt...");

    myFile.println("************ testing 1, 2, 3 ************");
    for(int ijk = 0; ijk < 25; ijk++)
    {
      myFile.print("   current millis() and micros() values are  ");
      myFile.print(millis());
      myFile.print("  ");
      myFile.println(micros());
    }
    myFile.println("************ all done! ************");

    // close the file:
    myFile.close();
    Serial.println("done: just closed file.\n");

  } else {

    // if the file didn't open, print an error:
    Serial.println("error opening test.txt\n");

  }

  // re-open the file for reading
  Serial.print("Now open test.txt, read it, and echo it to the serial monitor.");
  Serial.print("Initial millis()n value was ");
  Serial.println(millis_start);

  myFile = SD.open("test.txt");

  if (myFile) {
    Serial.println("test.txt:");

    // read from the file until there's nothing else in it:
    while (myFile.available()) 
    {
      Serial.write(myFile.read());
    }

    // close the file:
    myFile.close();
    Serial.println("we are finished: just closed file.\n");
  } else {

    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop() {
  // nothing happens after setup
}

