Code Example

/*
  SD card reader code written for the PJRC MicroSD card reader for use on
  a Teensy 3.1/3.2.
  Collect Data from a analog pin and writes the data to SD

  Written by Thomas Cifelli and Carson Shaw 2016.  
  This example code is in the public domain.

Teensy        SD Card
DOUT 11       MOSI
DIN  12       MISO  
SCK  13       SCLK
CS   10       SS
GND           GND
+5            +5
  
*/
#include <SD.h>; //necessary library for SD card use
#include <SPI.h>; //necessary library for SD card use
File file; //creates a file variable of a given name (in this case, "file")
int sensor = A2; //the pin of the sensor to be read
int delayTime = 1000; //how long to wait between sensor readings


void setup() {
  Serial.begin(9600); //initialized communication with the serial monitor
  while(!Serial); //waits for the serial monitor to be opened
  SD.begin(10); //starts reading the SD card on pin 10 (the CS pin)
  delay(100); //small delay to allow the monitor to fully open
  //SD.remove("DataFile.txt"); //use to clear the file when necessary
  file = SD.open("DataFile.txt"); //opens or creates a file of that name
  while(file.available()) { //prints all the data on the file to the serial monitor
    Serial.write(file.read());
  };
  Serial.println("--------------------------"); //separates the old data from the new
  file.close(); //closes the file (IMPORTANT)

}

void loop() {
  file = SD.open("DataFile.txt", FILE_WRITE); //opens the file so it can be written to
  int sensorData = analogRead(sensor); //reads the sensor
  Serial.println(sensorData); //prints the sensor data to the serial monitor
  file.print(sensorData); //writes the sensor data to the file
  file.println(); //creates a new line in the file
  file.flush(); //saves the file
  file.close(); //closes the file
  delay(delayTime); //waits until the delayTime is over
}