Not totally sure why this forked, but should be the same as the original SDFileSystem library

Dependencies:   FATFileSystem

Fork of SDFileSystem by mbed official

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers SDFileSystem.cpp Source File

SDFileSystem.cpp

00001 /* mbed Microcontroller Library
00002  * Copyright (c) 2006-2012 ARM Limited
00003  *
00004  * Permission is hereby granted, free of charge, to any person obtaining a copy
00005  * of this software and associated documentation files (the "Software"), to deal
00006  * in the Software without restriction, including without limitation the rights
00007  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
00008  * copies of the Software, and to permit persons to whom the Software is
00009  * furnished to do so, subject to the following conditions:
00010  *
00011  * The above copyright notice and this permission notice shall be included in
00012  * all copies or substantial portions of the Software.
00013  *
00014  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
00015  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
00016  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
00017  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
00018  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
00019  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
00020  * SOFTWARE.
00021  */
00022 
00023 /* Introduction
00024  * ------------
00025  * SD and MMC cards support a number of interfaces, but common to them all
00026  * is one based on SPI. This is the one I'm implmenting because it means
00027  * it is much more portable even though not so performant, and we already
00028  * have the mbed SPI Interface!
00029  *
00030  * The main reference I'm using is Chapter 7, "SPI Mode" of:
00031  *  http://www.sdcard.org/developers/tech/sdcard/pls/Simplified_Physical_Layer_Spec.pdf
00032  *
00033  * SPI Startup
00034  * -----------
00035  * The SD card powers up in SD mode. The SPI interface mode is selected by
00036  * asserting CS low and sending the reset command (CMD0). The card will
00037  * respond with a (R1) response.
00038  *
00039  * CMD8 is optionally sent to determine the voltage range supported, and
00040  * indirectly determine whether it is a version 1.x SD/non-SD card or
00041  * version 2.x. I'll just ignore this for now.
00042  *
00043  * ACMD41 is repeatedly issued to initialise the card, until "in idle"
00044  * (bit 0) of the R1 response goes to '0', indicating it is initialised.
00045  *
00046  * You should also indicate whether the host supports High Capicity cards,
00047  * and check whether the card is high capacity - i'll also ignore this
00048  *
00049  * SPI Protocol
00050  * ------------
00051  * The SD SPI protocol is based on transactions made up of 8-bit words, with
00052  * the host starting every bus transaction by asserting the CS signal low. The
00053  * card always responds to commands, data blocks and errors.
00054  *
00055  * The protocol supports a CRC, but by default it is off (except for the
00056  * first reset CMD0, where the CRC can just be pre-calculated, and CMD8)
00057  * I'll leave the CRC off I think!
00058  *
00059  * Standard capacity cards have variable data block sizes, whereas High
00060  * Capacity cards fix the size of data block to 512 bytes. I'll therefore
00061  * just always use the Standard Capacity cards with a block size of 512 bytes.
00062  * This is set with CMD16.
00063  *
00064  * You can read and write single blocks (CMD17, CMD25) or multiple blocks
00065  * (CMD18, CMD25). For simplicity, I'll just use single block accesses. When
00066  * the card gets a read command, it responds with a response token, and then
00067  * a data token or an error.
00068  *
00069  * SPI Command Format
00070  * ------------------
00071  * Commands are 6-bytes long, containing the command, 32-bit argument, and CRC.
00072  *
00073  * +---------------+------------+------------+-----------+----------+--------------+
00074  * | 01 | cmd[5:0] | arg[31:24] | arg[23:16] | arg[15:8] | arg[7:0] | crc[6:0] | 1 |
00075  * +---------------+------------+------------+-----------+----------+--------------+
00076  *
00077  * As I'm not using CRC, I can fix that byte to what is needed for CMD0 (0x95)
00078  *
00079  * All Application Specific commands shall be preceded with APP_CMD (CMD55).
00080  *
00081  * SPI Response Format
00082  * -------------------
00083  * The main response format (R1) is a status byte (normally zero). Key flags:
00084  *  idle - 1 if the card is in an idle state/initialising
00085  *  cmd  - 1 if an illegal command code was detected
00086  *
00087  *    +-------------------------------------------------+
00088  * R1 | 0 | arg | addr | seq | crc | cmd | erase | idle |
00089  *    +-------------------------------------------------+
00090  *
00091  * R1b is the same, except it is followed by a busy signal (zeros) until
00092  * the first non-zero byte when it is ready again.
00093  *
00094  * Data Response Token
00095  * -------------------
00096  * Every data block written to the card is acknowledged by a byte
00097  * response token
00098  *
00099  * +----------------------+
00100  * | xxx | 0 | status | 1 |
00101  * +----------------------+
00102  *              010 - OK!
00103  *              101 - CRC Error
00104  *              110 - Write Error
00105  *
00106  * Single Block Read and Write
00107  * ---------------------------
00108  *
00109  * Block transfers have a byte header, followed by the data, followed
00110  * by a 16-bit CRC. In our case, the data will always be 512 bytes.
00111  *
00112  * +------+---------+---------+- -  - -+---------+-----------+----------+
00113  * | 0xFE | data[0] | data[1] |        | data[n] | crc[15:8] | crc[7:0] |
00114  * +------+---------+---------+- -  - -+---------+-----------+----------+
00115  */
00116 #include "SDFileSystem.h"
00117 #include "mbed_debug.h"
00118 
00119 #define SD_COMMAND_TIMEOUT 5000
00120 
00121 #define SD_DBG             0
00122 
00123 SDFileSystem::SDFileSystem(PinName mosi, PinName miso, PinName sclk, PinName cs, const char* name) :
00124     FATFileSystem(name), _spi(mosi, miso, sclk), _cs(cs) {
00125     _cs = 1;
00126 }
00127 
00128 #define R1_IDLE_STATE           (1 << 0)
00129 #define R1_ERASE_RESET          (1 << 1)
00130 #define R1_ILLEGAL_COMMAND      (1 << 2)
00131 #define R1_COM_CRC_ERROR        (1 << 3)
00132 #define R1_ERASE_SEQUENCE_ERROR (1 << 4)
00133 #define R1_ADDRESS_ERROR        (1 << 5)
00134 #define R1_PARAMETER_ERROR      (1 << 6)
00135 
00136 // Types
00137 #define SDCARD_FAIL 0 //!< v1.x Standard Capacity
00138 #define SDCARD_V1   1 //!< v2.x Standard Capacity
00139 #define SDCARD_V2   2 //!< v2.x High Capacity
00140 #define SDCARD_V2HC 3 //!< Not recognised as an SD Card
00141 
00142 int SDFileSystem::initialise_card() {
00143     // Set to 100kHz for initialisation, and clock card with cs = 1
00144     _spi.frequency(100000);
00145     _cs = 1;
00146     for (int i = 0; i < 16; i++) {
00147         _spi.write(0xFF);
00148     }
00149     
00150     // send CMD0, should return with all zeros except IDLE STATE set (bit 0)
00151     if (_cmd(0, 0) != R1_IDLE_STATE) {
00152         debug("No disk, or could not put SD card in to SPI idle state\n");
00153         return SDCARD_FAIL;
00154     }
00155     
00156     // send CMD8 to determine whther it is ver 2.x
00157     int r = _cmd8();
00158     if (r == R1_IDLE_STATE) {
00159         return initialise_card_v2();
00160     } else if (r == (R1_IDLE_STATE | R1_ILLEGAL_COMMAND)) {
00161         return initialise_card_v1();
00162     } else {
00163         debug("Not in idle state after sending CMD8 (not an SD card?)\n");
00164         return SDCARD_FAIL;
00165     }
00166 }
00167 
00168 int SDFileSystem::initialise_card_v1() {
00169     for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
00170         _cmd(55, 0);
00171         if (_cmd(41, 0) == 0) {
00172             cdv = 512;
00173             debug_if(SD_DBG, "\n\rInit: SEDCARD_V1\n\r");
00174             return SDCARD_V1;
00175         }
00176     }
00177     
00178     debug("Timeout waiting for v1.x card\n");
00179     return SDCARD_FAIL;
00180 }
00181 
00182 int SDFileSystem::initialise_card_v2() {
00183     for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
00184         wait_ms(50);
00185         _cmd58();
00186         _cmd(55, 0);
00187         if (_cmd(41, 0x40000000) == 0) {
00188             _cmd58();
00189             debug_if(SD_DBG, "\n\rInit: SDCARD_V2\n\r");
00190             cdv = 1;
00191             return SDCARD_V2;
00192         }
00193     }
00194     
00195     debug("Timeout waiting for v2.x card\n");
00196     return SDCARD_FAIL;
00197 }
00198 
00199 int SDFileSystem::disk_initialize() {
00200     int i = initialise_card();
00201     debug_if(SD_DBG, "init card = %d\n", i);
00202     _sectors = _sd_sectors();
00203     
00204     // Set block length to 512 (CMD16)
00205     if (_cmd(16, 512) != 0) {
00206         debug("Set 512-byte block timed out\n");
00207         return 1;
00208     }
00209     
00210     _spi.frequency(1000000); // Set to 1MHz for data transfer
00211     return 0;
00212 }
00213 
00214 int SDFileSystem::disk_write(const uint8_t *buffer, uint64_t block_number, uint8_t count) {
00215     while (count--) {
00216     // set write address for single block (CMD24)
00217     if (_cmd(24, block_number * cdv) != 0) {
00218         return 1;
00219     }
00220     
00221     // send the data block
00222     _write(buffer, 512);
00223     buffer+=512;
00224     block_number++;
00225     }
00226     return 0;
00227 }
00228 
00229 int SDFileSystem::disk_read(uint8_t *buffer, uint64_t block_number,uint8_t count) {
00230     while (count--) {
00231     // set read address for single block (CMD17)
00232     if (_cmd(17, block_number * cdv) != 0) {
00233         return 1;
00234     }
00235     
00236     // receive the data
00237     _read(buffer, 512);
00238     buffer+=512;
00239     block_number++;
00240     }
00241     return 0;
00242 }
00243 
00244 int SDFileSystem::disk_status() { return 0; }
00245 int SDFileSystem::disk_sync() { return 0; }
00246 uint64_t SDFileSystem::disk_sectors() { return _sectors; }
00247 
00248 
00249 // PRIVATE FUNCTIONS
00250 int SDFileSystem::_cmd(int cmd, int arg) {
00251     _cs = 0;
00252     
00253     // send a command
00254     _spi.write(0x40 | cmd);
00255     _spi.write(arg >> 24);
00256     _spi.write(arg >> 16);
00257     _spi.write(arg >> 8);
00258     _spi.write(arg >> 0);
00259     _spi.write(0x95);
00260     
00261     // wait for the repsonse (response[7] == 0)
00262     for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
00263         int response = _spi.write(0xFF);
00264         if (!(response & 0x80)) {
00265             _cs = 1;
00266             _spi.write(0xFF);
00267             return response;
00268         }
00269     }
00270     _cs = 1;
00271     _spi.write(0xFF);
00272     return -1; // timeout
00273 }
00274 int SDFileSystem::_cmdx(int cmd, int arg) {
00275     _cs = 0;
00276     
00277     // send a command
00278     _spi.write(0x40 | cmd);
00279     _spi.write(arg >> 24);
00280     _spi.write(arg >> 16);
00281     _spi.write(arg >> 8);
00282     _spi.write(arg >> 0);
00283     _spi.write(0x95);
00284     
00285     // wait for the repsonse (response[7] == 0)
00286     for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
00287         int response = _spi.write(0xFF);
00288         if (!(response & 0x80)) {
00289             return response;
00290         }
00291     }
00292     _cs = 1;
00293     _spi.write(0xFF);
00294     return -1; // timeout
00295 }
00296 
00297 
00298 int SDFileSystem::_cmd58() {
00299     _cs = 0;
00300     int arg = 0;
00301     
00302     // send a command
00303     _spi.write(0x40 | 58);
00304     _spi.write(arg >> 24);
00305     _spi.write(arg >> 16);
00306     _spi.write(arg >> 8);
00307     _spi.write(arg >> 0);
00308     _spi.write(0x95);
00309     
00310     // wait for the repsonse (response[7] == 0)
00311     for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
00312         int response = _spi.write(0xFF);
00313         if (!(response & 0x80)) {
00314             int ocr = _spi.write(0xFF) << 24;
00315             ocr |= _spi.write(0xFF) << 16;
00316             ocr |= _spi.write(0xFF) << 8;
00317             ocr |= _spi.write(0xFF) << 0;
00318             _cs = 1;
00319             _spi.write(0xFF);
00320             return response;
00321         }
00322     }
00323     _cs = 1;
00324     _spi.write(0xFF);
00325     return -1; // timeout
00326 }
00327 
00328 int SDFileSystem::_cmd8() {
00329     _cs = 0;
00330     
00331     // send a command
00332     _spi.write(0x40 | 8); // CMD8
00333     _spi.write(0x00);     // reserved
00334     _spi.write(0x00);     // reserved
00335     _spi.write(0x01);     // 3.3v
00336     _spi.write(0xAA);     // check pattern
00337     _spi.write(0x87);     // crc
00338     
00339     // wait for the repsonse (response[7] == 0)
00340     for (int i = 0; i < SD_COMMAND_TIMEOUT * 1000; i++) {
00341         char response[5];
00342         response[0] = _spi.write(0xFF);
00343         if (!(response[0] & 0x80)) {
00344             for (int j = 1; j < 5; j++) {
00345                 response[i] = _spi.write(0xFF);
00346             }
00347             _cs = 1;
00348             _spi.write(0xFF);
00349             return response[0];
00350         }
00351     }
00352     _cs = 1;
00353     _spi.write(0xFF);
00354     return -1; // timeout
00355 }
00356 
00357 int SDFileSystem::_read(uint8_t *buffer, uint32_t length) {
00358     _cs = 0;
00359     
00360     // read until start byte (0xFF)
00361     while (_spi.write(0xFF) != 0xFE);
00362     
00363     // read data
00364     for (int i = 0; i < length; i++) {
00365         buffer[i] = _spi.write(0xFF);
00366     }
00367     _spi.write(0xFF); // checksum
00368     _spi.write(0xFF);
00369     
00370     _cs = 1;
00371     _spi.write(0xFF);
00372     return 0;
00373 }
00374 
00375 int SDFileSystem::_write(const uint8_t*buffer, uint32_t length) {
00376     _cs = 0;
00377     
00378     // indicate start of block
00379     _spi.write(0xFE);
00380     
00381     // write the data
00382     for (int i = 0; i < length; i++) {
00383         _spi.write(buffer[i]);
00384     }
00385     
00386     // write the checksum
00387     _spi.write(0xFF);
00388     _spi.write(0xFF);
00389     
00390     // check the response token
00391     if ((_spi.write(0xFF) & 0x1F) != 0x05) {
00392         _cs = 1;
00393         _spi.write(0xFF);
00394         return 1;
00395     }
00396     
00397     // wait for write to finish
00398     while (_spi.write(0xFF) == 0);
00399     
00400     _cs = 1;
00401     _spi.write(0xFF);
00402     return 0;
00403 }
00404 
00405 static uint32_t ext_bits(unsigned char *data, int msb, int lsb) {
00406     uint32_t bits = 0;
00407     uint32_t size = 1 + msb - lsb;
00408     for (int i = 0; i < size; i++) {
00409         uint32_t position = lsb + i;
00410         uint32_t byte = 15 - (position >> 3);
00411         uint32_t bit = position & 0x7;
00412         uint32_t value = (data[byte] >> bit) & 1;
00413         bits |= value << i;
00414     }
00415     return bits;
00416 }
00417 
00418 uint64_t SDFileSystem::_sd_sectors() {
00419     uint32_t c_size, c_size_mult, read_bl_len;
00420     uint32_t block_len, mult, blocknr, capacity;
00421     uint32_t hc_c_size;
00422     uint64_t blocks;
00423     
00424     // CMD9, Response R2 (R1 byte + 16-byte block read)
00425     if (_cmdx(9, 0) != 0) {
00426         debug("Didn't get a response from the disk\n");
00427         return 0;
00428     }
00429     
00430     uint8_t csd[16];
00431     if (_read(csd, 16) != 0) {
00432         debug("Couldn't read csd response from disk\n");
00433         return 0;
00434     }
00435     
00436     // csd_structure : csd[127:126]
00437     // c_size        : csd[73:62]
00438     // c_size_mult   : csd[49:47]
00439     // read_bl_len   : csd[83:80] - the *maximum* read block length
00440     
00441     int csd_structure = ext_bits(csd, 127, 126);
00442     
00443     switch (csd_structure) {
00444         case 0:
00445             cdv = 512;
00446             c_size = ext_bits(csd, 73, 62);
00447             c_size_mult = ext_bits(csd, 49, 47);
00448             read_bl_len = ext_bits(csd, 83, 80);
00449             
00450             block_len = 1 << read_bl_len;
00451             mult = 1 << (c_size_mult + 2);
00452             blocknr = (c_size + 1) * mult;
00453             capacity = blocknr * block_len;
00454             blocks = capacity / 512;
00455             debug_if(SD_DBG, "\n\rSDCard\n\rc_size: %d \n\rcapacity: %ld \n\rsectors: %lld\n\r", c_size, capacity, blocks);
00456             break;
00457         
00458         case 1:
00459             cdv = 1;
00460             hc_c_size = ext_bits(csd, 63, 48);
00461             blocks = (hc_c_size+1)*1024;
00462             debug_if(SD_DBG, "\n\rSDHC Card \n\rhc_c_size: %d\n\rcapacity: %lld \n\rsectors: %lld\n\r", hc_c_size, blocks*512, blocks);
00463             break;
00464         
00465         default:
00466             debug("CSD struct unsupported\r\n");
00467             return 0;
00468     };
00469     return blocks;
00470 }