Arduino Library

Arduino Library & First Test

Interfacing with an SD card is a bunch of work, but luckily for us, Adafruit customer fat16lib (William G) has written a very nice Arduino library just for this purpose and it's now part of the Arduino IDE known as SD (pretty good name, right?) You can see it in the Examples submenu

Next, select the CardInfo example sketch.

This sketch will not write any data to the card, just tell you if it managed to recognize it, and some information about it. This can be very useful when trying to figure out whether an SD card is supported. Before trying out a new card, please try out this sketch!

Go to the beginning of the sketch and make sure that the chipSelect line is correct, for this wiring we're using digital pin 10 so change it to 10!

OK, now insert the SD card into the breakout board and upload the sketch.

Open up the Serial Monitor and type in a character into the text box (& hit send) when prompted. You'll probably get something like the following:

It's mostly gibberish, but it's useful to see the Volume type is FAT16 part as well as the size of the card (about 2 GB which is what it should be) etc.

If you have a bad card, which seems to happen more with ripoff version of good brands, you might see:

The card mostly responded, but the data is all bad. Note that the Product ID is "N/A" and there is no Manufacturer ID or OEM ID. This card returned some SD errors. It's basically a bad scene, I only keep this card around to use as an example of a bad card! If you get something like this (where there is a response but it's corrupted) you can try to reformat it or if it still flakes out, should toss the card.

Finally, try taking out the SD card and running the sketch again, you'll get the following,

It couldn't even initialize the SD card. This can also happen if there's a soldering or wiring error or if the card is really damaged.

Writing files

The following sketch will do a basic demonstration of writing to a file. This is a common desire for datalogging and such.

#include <SD.h>
 
File myFile;
 
void setup()
{
  Serial.begin(9600);
  Serial.print("Initializing SD card...");
  // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
  // Note that even if it's not used as the CS pin, the hardware SS pin 
  // (10 on most Arduino boards, 53 on the Mega) must be left as an output 
  // or the SD library functions will not work. 
   pinMode(10, OUTPUT);
 
  if (!SD.begin(10)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");
 
  // 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);
 
  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("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");
  }
}
 
void loop()
{
	// nothing happens after setup
}
When you run it you should see the following:
You can then open up the file in your operating system by inserting the card. You'll see one line for each time the sketch ran. That is to say, it appends to the file, not overwriting it.

Some things to note:

  • You can have multiple files open at a time, and write to each one as you wish.
  • You can use print and println() just like Serial objects, to write strings, variables, etc
  • You must close() the file(s) when you're done to make sure all the data is written permanently!
  • You can open files in a directory. For example, if you want to open a file in the directory such as /MyFiles/example.txt you can call SD.open("/myfiles/example.txt") and it will do the right thing.
The SD card library does not support 'long filenames' such as we are used to. Instead, it uses the 8.3 format for file names, so keep file names short! For example IMAGE.JPG is fine, and datalog.txt is fine but "My GPS log file.text" is not! Also keep in mind that short file names do not have 'case' sensitivity, so datalog.txt is the same file as DataLog.Txt is the same file as DATALOG.TXT

Reading from files

Next up we will show how to read from a file, it's very similar to writing in that we SD.open() the file but this time we don't pass in the argument FILE_WRITE this will keep you from accidentally writing to it. You can then call available() (which will let you know if there is data left to be read) and read() from the file, which will return the next byte.

#include <SD.h>
 
File myFile;
 
void setup()
{
  Serial.begin(9600);
  Serial.print("Initializing SD card...");
  // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
  // Note that even if it's not used as the CS pin, the hardware SS pin 
  // (10 on most Arduino boards, 53 on the Mega) must be left as an output 
  // or the SD library functions will not work. 
   pinMode(10, OUTPUT);
 
  if (!SD.begin(10)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");
 
  // open the file for reading:
  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();
  } else {
  	// if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}
 
void loop()
{
	// nothing happens after setup
}

Some things to note:

  • You can have multiple files open at a time, and read from each one as you wish.
  • Read() only returns a byte at a time. It does not read a full line or a number!
  • You should close() the file(s) when you're done to reduce the amount of RAM used.
The SD card library does not support 'long filenames' such as we are used to. Instead, it uses the 8.3 format for file names, so keep file names short! For example IMAGE.JPG is fine, and datalog.txt is fine by "My GPS log file.text" is not! Also keep in mind that short file names do not have 'case' sensitivity, so datalog.txt is the same file as DataLog.Txt is the same file as DATALOG.TXT

Recursively listing/reading files

The last example we have shows more advanced use. A common request is for example wanting to list every file on the SD card, or play ever music file or similar. In the latest version of the SD library, you can recurse through a directory and call openNextFile() to get the next available file. These aren't in alphabetical order, they're in order of creation so just watch out for that!

To see it, run the SD→listfiles example sketch

Here you can see that we have a subdirectory ANIM (we have animation files in it). The numbers after each file name are the size in bytes of the file. This sketch is handy if you want to check what files are called on your card. The sketch also demonstrates how to do directory handling.

Last updated on 2017-11-26 at 04.46.52 PM Published on 2013-07-31 at 10.50.50 AM