SD Card

In this project, you'll learn how to read and write files to an SD card. SD cards are like your thumb drives where you can store large files on non-volatile removable media.

Parts needed:
  • Arduino
  • Micro SD card module
  • Micro SD card
Arduino
SD card module   Micro SD card
1 Requires the built-in SPI library for communication between the Arduino and the SD card module, and the SD library for file access on the SD card. Both of these libraries are already installed as part of your Arduino installation.
2 Making the connections

The SD card module requires six connections to the Arduino:
MOSI, MISO, CLK, CS, VCC and GND.

SD Card Arduino Description
MOSI 11 SPI communication
MISO 12 SPI communication
CLK 13 SPI clock
CS 10 Chip select
VCC 5V Power
GND GND GND
3 Here's the code to write and read a file to the SD card.
#include <SPI.h>
#include <SD.h>
#define CS 10

File myFile;

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

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

  if (!SD.begin(CS)) {  // pin that CS is connected to
    Serial.println("initialization failed");
    return;
  }
  Serial.println("initialization done");

  if (SD.exists("test.txt")) {
    Serial.println("File test.txt already exists. Deleting it");
    SD.remove("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.
  // this actually appends to the file if it already exists
  myFile = SD.open("test.txt", FILE_WRITE);

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("RobotsForFun testing 1, 2, 3.");
    // close the file:
    myFile.close();
    Serial.println("done");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }

  // re-open the file for reading:
  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("Reading from test.txt...");

    // read from the file and output to serial monitor until there's nothing in it
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    // close the file:
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop() {
}