User Tools

Site Tools


tutorials:products:microsd:index.html

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
tutorials:products:microsd:index.html [2011/07/28 20:57]
daigo [Reading from files]
tutorials:products:microsd:index.html [2016/01/28 18:05] (current)
Line 1: Line 1:
-   +====== ​Moved! ======
-==== Introduction  ​==== +
-[[http://​www.ladyada.net/​images/​microsd/​microsdbb.jpg|{{ ​ http://​www.ladyada.net/​images/​microsd/​microsdbb_t.jpg?​nolink&​500x307 ​ |}}]] +
- +
- +
- +
-If you have a project with any audio, video, graphics, data logging, etc in it, you'll find that having a removable storage option is essential. Most microcontrollers have extremely limited built-in storage. For example, even the Arduino Mega chip (the Atmega2560) has a mere 4Kbytes of EEPROM storage. There'​s more flash (256K) but you cant write to it as easily and you have to be careful if you want to store information in flash that you don't overwrite the program itself! +
- +
-[[http://​www.ladyada.net/​images/​microsd/​cards.jpg|{{ ​ http://​www.ladyada.net/​images/​microsd/​cards_t.jpg?​nolink&​500x387 ​ |}}]] +
- +
- +
- +
-If you're doing any sort of data logging, graphics or audio, you'll need at least a megabyte of storage, and 64 M is probably the minimum. To get that kind of storage we're going to use the same type that's in every digital camera and mp3 player: flash cards! Often called SD or microSD cards, they can pack** gigabytes** into a space smaller than a coin. They'​re also available in every elecronics shop so you can easily get more and best of all, many computers have SD or microSD card readers built in so you can move data back and forth between say your Arduino GPS data logger and your computer graphing software: +
- +
-{{  http://​www.ladyada.net/​images/​wavshield/​SADSDDR99A15.PNG.jpg?​nolink&​380x380 ​ |}} +
- +
- +
-==== What to watch for!  ==== +
- +
- +
-There are a few things to watch for when interacting with SD cards: +
- +
- +
- +
-One is that they are strictly 3.3V devices and the power draw when writing to the card can be fairly high, up to 100mA (or more)! That means that you **must **have a fairly good 3.3V power supply for the card. Secondly you must also have 3.3V logic to interface to the pins. We've found that SD cards are fairly sensitive about the interface pins - the newest cards are edge triggered and require very '​square'​ transitions - things like resistor dividers and long wires will have a deleterious effect on the transition speed, so **keep wires short, and avoid using resistor dividers for the 3.3V logic lines**. We suggest instead using level shifters, such as **HEF4050**,​ **74LVX245 **or **74AHC125** chips. +
- +
- +
- +
-Secondly, there are two ways to interface with SD cards - **SPI mode** and **SDIO** **mode**. SDIO mode is faster, but is more complex and as far as we can tell, requires signing non-disclosure documents. For that reason, you will likely never encounter SDIO mode interface code. Instead, every SD card has a 'lower speed' SPI mode that is easy for any microcontroller to use. SPI mode requires four pins (we'll discuss them in detail later) so its not pin-heavy like some parallel-interface components +
- +
- +
- +
-SD cards come in two popular flavors - **microSD** and **SD**. The interface, code, structure, etc is all the same. The only differences is the size. MicroSD are much much smaller in physical size. +
- +
- +
- +
-Third, SD cards are '​raw'​ storage. They'​re just sectors in a flash chip, there'​s no structure that you //have //to use. That means you could format an SD card to be a Linux filesystem, a FAT (DOS) filesystem or a Mac filesystem. You could also not have any filesystem at all! However, 99% of computers, cameras, MP3 players, GPS loggers, etc require **FAT16** or **FAT32** for the filesystem. The tradeoff here is that for smaller microcontrollers (like the Arduino) the addition of the complex file format handling can take a lot of flash storage and RAM +
- +
- +
-==== Formatting notes  ==== +
- +
- +
-Even though you can could use your SD card '​raw'​ - its most convenient to format the card to a filesystem. For the Arduino library we'll be discussing, and nearly every other SD library, the card must be formatted FAT16 or FAT32. Some only allow one or the other. The Arduino SD library can use either. Note that the vast vast majority of SD cards come preformatted out of the box so **don'​t format the card unless you're sure you need to!** Most of the time, its OK as is! +
- +
- +
-==== Formatting under Mac OS  ==== +
- +
- +
-To format the SD card, you will need the path to the SD card device and the SD card device number.  +
- +
- +
-  *Insert the SD Card into a card reader. ​ \\  +
-  *Open** Disk Utility ** +
-  *Highlight the SD Card **device** (upper icon), not the SD Card volume (lower icon)  +
-  *Click **Erase** at the top of the window  +
-  *Select **Volume Format: MS-DOS (FAT)** Click** Erase... >** Click **Erase ** +
-  *It is now formatted in MS-DOS FAT32   +
-==== Formatting under Windows ​ ==== +
- +
- +
-If your card is not formatted properly, its pretty easy to do and you only need to do it once. To format the card, place it into your card reader, then right click on the disk and select **Format...** +
- +
-{{  http://​www.ladyada.net/​images/​wavshield/​format.gif?​nolink&​516x387 ​ |}}  +
- +
-Make sure that in the **File system ** pulldown menu, that **FAT** +
- +
-{{  http://​www.ladyada.net/​images/​wavshield/​fatformat.gif?​nolink&​257x401 ​ |}} +
- +
-And click **Start** +
- +
-If you get the** Properties **of the card you will see it is FAT formatted. This card has some files on it so its not completely empty  +
- +
-{{  http://​www.ladyada.net/​images/​wavshield/​fatprop.gif?​nolink&​367x455 ​ |}}  +
- +
- +
-==== Wiring ​ ==== +
- +
- +
-Now that your card is ready to use, we can wire up the microSD breakout board! The breakout board we designed takes care of a lot for you. There'​s an onboard ultra-low dropout regulator that will convert voltages from 3.3V-6v down to ~3.3V (**IC2**). There'​s also a level shifter that will convert the interface logic from 3.3V-5V to 3.3V. That means you can use this board to interact with a 3.3V or 5V microcontrollers. +
- +
-[[http://​www.ladyada.net/​images/​microsd/​microsdbb.jpg|{{ ​ http://​www.ladyada.net/​images/​microsd/​microsdbb_t.jpg?​nolink&​500x307 ​ |}}]] +
- +
-In this tutorial we will be using an Arduino to demonstrate the wiring and interfacing. If you have another microcontroller,​ you'll need to adapt the wiring and code to match! +
- +
-Because SD cards require a lot of data transfer, they'​re really only good when connected up to the **hardware** SPI pins on a microcontroller. The hardware SPI pins are much faster than '​bit-banging'​ the interface code using another set of pins. For '​classic'​ Arduinos such as the Duemilanove/​Diecimila/​Uno those pins are **digital 13 (SCK), 12 (MISO) **and **11 (MISO)**. You will also need a fourth pin for the '​chip/​slave select'​ (**SS**) line. Traditionally this is pin **10 **but you can actually use any pin you like. If you have a Mega, the pins are different! You'll want to use digital ** 50 (MISO), 51 (MOSI), 52 (SCK), **and for the CS line, the most common pin is **53 (SS).** Again, you can change the SS (pin **10** or **53**) later but for now, stick with those pins. +
- +
- +
-  *Connect the **5V** pin to the **5V** pin on the Arduino +
-  *Connect the** GND **pin to the** GND **pin on the Arduino +
-  *Connect **CLK** to pin **13 ** or **52 ** +
-  *Connect **DO **to pin **12 ** or **50 ** +
-  *Connect **DI** to pin **11 ** or **51** +
-  *Connect **CS **to pin **10 ** or **53 ** +
- +
-There'​s one more pin **CD** - this is the Card Detect pin. It shorts to ground when a card is inserted. You should connect a pull up resistor (10K or so) and wire this to another pin if you want to detect when a card is inserted. We won't be using it for now +
- +
-[[http://​www.ladyada.net/​images/​microsd/​microsdwiring.jpg|{{ ​ http://​www.ladyada.net/​images/​microsd/​microsdwiring_t.jpg?​nolink&​500x383 ​ |}}]] +
- +
- +
- +
-That's it! Now you're ready to rock +
- +
- +
-==== 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 its now part of the Arduino IDE known as **SD** (pretty good name, right?)  +
- +
- +
- +
-The only problem is that we've made a few nice updates to the SD library which are not in Arduino v22. So if you're using v22 please install our revision as follows! +
- +
- +
- +
-[[https://​github.com/​adafruit/​SD|Download the library]] by clicking the **DOWNLOAD** button at the top right. ​ Then make a backup of the folder called **SD** in your **ArduinoIDE/​libraries** folder (on a Mac you will have to '​explore'​ the App). Then uncompress the newly downloaded folder and rename it **SD**. Inside the **SD** folder you should see **README.txt** and other files. Install it by dragging it in your **ArduinoIDE/​libraries** folder and restarting the IDE +
- +
- +
- +
-Next, select the** CardInfo** example sketch +
- +
-{{  http://​www.ladyada.net/​images/​logshield/​opencardinfo.gif?​nolink&​498x600 ​ |}} +
- +
-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! +
- +
-{{  http://​www.ladyada.net/​images/​logshield/​cardinfocs.gif?​nolink&​500x600 ​ |}} +
- +
-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:​ +
- +
-{{  http://​www.ladyada.net/​images/​logshield/​cardinfook.gif?​nolink&​513x498 ​ |}} +
- +
-Its mostly gibberish, but its 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: \\  +
- +
-{{  http://​www.ladyada.net/​images/​logshield/​badsdinfo.gif?​nolink&​404x553 ​ |}} +
- +
-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. Its 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 its 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,​ +
- +
-{{  http://​www.ladyada.net/​images/​logshield/​cardinfonone.gif?​nolink&​513x194 ​ |}} +
- +
- 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 +
- +
- +
-==== Reading files  ==== +
- +
- +
-The following sketch will do a basic demonstration of writing to a file. This is a common desire for datalogging and such +
- +
-<code C> +
-#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 +
-+
- +
-</​code>​ +
- +
-When you run it you should see the following:​ +
- +
-{{  http://​www.ladyada.net/​images/​microsd/​writetest.gif?​nolink&​407x232 ​ |}} +
- +
-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. +
- +
-{{  http://​www.ladyada.net/​images/​microsd/​writtentest.gif?​nolink&​377x201 ​ |}} +
- +
-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 +
- +
-<class warning>​ +
-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** +
-</​class>​ +
- +
-==== Reading from files  ==== +
- +
- +
-Next up we will show how to read from a file, its 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. +
- +
-<code C> +
-#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 +
-+
- +
-</​code>​ +
- +
-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 +
- +
-<class warning>​ +
-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** +
-</​class>​ +
- +
-==== 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 //recuse// 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 +
- +
-{{  http://​www.ladyada.net/​images/​microsd/​listrecuse.gif?​nolink&​642x591 ​ |}} +
- +
- +
-==== Other useful functions ​ ==== +
- +
- +
-There'​s a few useful things you can do with **SD** objects we'll list a few here: +
- +
- +
-  *If you just want to check if a file exists, use** SD.exists("​filename.txt"​) **which will return true or false  +
-  *You can delete a file by calling **SD.remove("​unwanted.txt"​)** - be careful! This will really delete it, and there'​s no 'trash can' to pull it out of. +
-  *You can create a subdirectory by calling **SD.mkdir("/​mynewdir"​) **handy when you want to stuff files in a location. Nothing happens if it already exists but you can always call **SD.exists() **above first +
- +
-Also, there'​s a few useful things you can do with **File** objects: +
- +
- +
-  *You can **seek()** on a file. This will move the reading/​writing pointer to a new location. For example **seek(0****)** will take you to the beginning of the file, which can be very handy! +
-  *Likewise you can call **position()** which will tell you where you are in the file. +
-  *If you want to know the size of a file, call **size() **to get the number of bytes in the file. +
-  *Directories/​folders are special files, you can determine if a file is a directory by calling **isDirectory()** +
-  *Once you have a directory, you can start going through all the files in the directory by calling **openNextFile()** +
-  *You may end up with needing to know the name of a file, say if you called **openNextFile()** on a directory. In this case, call **name()** which will return a pointer to the 8.3-formatted character array you can directly **Serial.print() **if you want.  +
-==== More examples! ​ ==== +
- +
- +
-If you want to use an SD card for datalogging,​ we suggest checking out our [[http://​www.ladyada.net/​make/​logshield|Datalogging shield]] and [[http://​www.ladyada.net/​make/​gpsshield/​|GPS logging shield]] - there'​s example code specifically for those purposes. +
- +
- +
- +
-If you want to use the SD card for loading images (such as for a color display) look at our [[http://​www.ladyada.net/​products/​tfttouchshield/​|2.8"​ TFT shield]] and [[http://​www.ladyada.net/​products/​18tftbreakout/​|1.8"​ TFT breakout tutorials]]. Those have examples of how we read BMP files off disk and parse them +
- +
- +
-==== Download  ​==== +
- +
- +
-[[http://​www.adafruit.com/​datasheets/​TS16GUSDHC6.pdf|Transcend microSD card datasheet]] +
- +
- +
- +
-[[https://​github.com/​adafruit/​SD|Our latest SD card library version ]]- download it by clicking DOWNLOADS at the top right. Then make a backup of the folder called **SD** in your **ArduinoIDE/​libraries** folder (on a Mac you will have to '​explore'​ the App). Then uncompress the newly downloaded folder and rename it **SD**. Inside the **SD** folder you should see **README.txt** and other files. Install it by dragging it in your **ArduinoIDE/​libraries** folder and restarting the IDE +
- +
-   +
- +
-  +
  
 +[[http://​learn.adafruit.com/​adafruit-micro-sd-breakout-board-card-tutorial|This tutorial has moved to http://​learn.adafruit.com/​adafruit-micro-sd-breakout-board-card-tutorial]]
/home/ladyada/public_html/wiki/data/attic/tutorials/products/microsd/index.html.1311886677.txt.gz · Last modified: 2016/01/28 18:05 (external edit)