This is SDFileSystem which corrected the bug for MiMicSDK.

Dependents:   MbedFileServer_1768MiniDK2 RedWireBridge IssueDebug_gcc MiMicRemoteMCU-for-Mbed ... more

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 /* Introduction
00023  * ------------
00024  * SD and MMC cards support a number of interfaces, but common to them all
00025  * is one based on SPI. This is the one I'm implmenting because it means
00026  * it is much more portable even though not so performant, and we already
00027  * have the mbed SPI Interface!
00028  *
00029  * The main reference I'm using is Chapter 7, "SPI Mode" of:
00030  *  http://www.sdcard.org/developers/tech/sdcard/pls/Simplified_Physical_Layer_Spec.pdf
00031  *
00032  * SPI Startup
00033  * -----------
00034  * The SD card powers up in SD mode. The SPI interface mode is selected by
00035  * asserting CS low and sending the reset command (CMD0). The card will
00036  * respond with a (R1) response.
00037  *
00038  * CMD8 is optionally sent to determine the voltage range supported, and
00039  * indirectly determine whether it is a version 1.x SD/non-SD card or
00040  * version 2.x. I'll just ignore this for now.
00041  *
00042  * ACMD41 is repeatedly issued to initialise the card, until "in idle"
00043  * (bit 0) of the R1 response goes to '0', indicating it is initialised.
00044  *
00045  * You should also indicate whether the host supports High Capicity cards,
00046  * and check whether the card is high capacity - i'll also ignore this
00047  *
00048  * SPI Protocol
00049  * ------------
00050  * The SD SPI protocol is based on transactions made up of 8-bit words, with
00051  * the host starting every bus transaction by asserting the CS signal low. The
00052  * card always responds to commands, data blocks and errors.
00053  *
00054  * The protocol supports a CRC, but by default it is off (except for the
00055  * first reset CMD0, where the CRC can just be pre-calculated, and CMD8)
00056  * I'll leave the CRC off I think!
00057  *
00058  * Standard capacity cards have variable data block sizes, whereas High
00059  * Capacity cards fix the size of data block to 512 bytes. I'll therefore
00060  * just always use the Standard Capacity cards with a block size of 512 bytes.
00061  * This is set with CMD16.
00062  *
00063  * You can read and write single blocks (CMD17, CMD25) or multiple blocks
00064  * (CMD18, CMD25). For simplicity, I'll just use single block accesses. When
00065  * the card gets a read command, it responds with a response token, and then
00066  * a data token or an error.
00067  *
00068  * SPI Command Format
00069  * ------------------
00070  * Commands are 6-bytes long, containing the command, 32-bit argument, and CRC.
00071  *
00072  * +---------------+------------+------------+-----------+----------+--------------+
00073  * | 01 | cmd[5:0] | arg[31:24] | arg[23:16] | arg[15:8] | arg[7:0] | crc[6:0] | 1 |
00074  * +---------------+------------+------------+-----------+----------+--------------+
00075  *
00076  * As I'm not using CRC, I can fix that byte to what is needed for CMD0 (0x95)
00077  *
00078  * All Application Specific commands shall be preceded with APP_CMD (CMD55).
00079  *
00080  * SPI Response Format
00081  * -------------------
00082  * The main response format (R1) is a status byte (normally zero). Key flags:
00083  *  idle - 1 if the card is in an idle state/initialising
00084  *  cmd  - 1 if an illegal command code was detected
00085  *
00086  *    +-------------------------------------------------+
00087  * R1 | 0 | arg | addr | seq | crc | cmd | erase | idle |
00088  *    +-------------------------------------------------+
00089  *
00090  * R1b is the same, except it is followed by a busy signal (zeros) until
00091  * the first non-zero byte when it is ready again.
00092  *
00093  * Data Response Token
00094  * -------------------
00095  * Every data block written to the card is acknowledged by a byte
00096  * response token
00097  *
00098  * +----------------------+
00099  * | xxx | 0 | status | 1 |
00100  * +----------------------+
00101  *              010 - OK!
00102  *              101 - CRC Error
00103  *              110 - Write Error
00104  *
00105  * Single Block Read and Write
00106  * ---------------------------
00107  *
00108  * Block transfers have a byte header, followed by the data, followed
00109  * by a 16-bit CRC. In our case, the data will always be 512 bytes.
00110  *
00111  * +------+---------+---------+- -  - -+---------+-----------+----------+
00112  * | 0xFE | data[0] | data[1] |        | data[n] | crc[15:8] | crc[7:0] |
00113  * +------+---------+---------+- -  - -+---------+-----------+----------+
00114  */
00115 #include "SDFileSystem.h"
00116 
00117 
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 //  - v1.x Standard Capacity
00138 //  - v2.x Standard Capacity
00139 //  - v2.x High Capacity
00140 //  - Not recognised as an SD Card
00141 #define SDCARD_FAIL 0
00142 #define SDCARD_V1   1
00143 #define SDCARD_V2   2
00144 #define SDCARD_V2HC 3
00145 
00146 int SDFileSystem::initialise_card() {
00147 
00148     // Set to 100kHz for initialisation, and clock card with cs = 1
00149     _spi.frequency(100000);
00150     _cs = 1;
00151     for (int i = 0; i < 16; i++) {
00152         _spi.write(0xFF);
00153     }
00154     
00155     // send CMD0, should return with all zeros except IDLE STATE set (bit 0)
00156     if (_cmd(0, 0) != R1_IDLE_STATE) {
00157         return SDCARD_FAIL;
00158     }
00159     
00160     // send CMD8 to determine whther it is ver 2.x
00161     int r = _cmd8();
00162     if (r == R1_IDLE_STATE) {
00163         return initialise_card_v2();
00164     } else if (r == (R1_IDLE_STATE | R1_ILLEGAL_COMMAND)) {
00165         return initialise_card_v1();
00166     } else {
00167         return SDCARD_FAIL;
00168     }
00169 }
00170 
00171 int SDFileSystem::initialise_card_v1() {
00172     for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
00173         _cmd(55, 0);
00174         if (_cmd(41, 0) == 0) {
00175             cdv = 512;
00176             return SDCARD_V1;
00177         }
00178     }
00179     
00180     return SDCARD_FAIL;
00181 }
00182 
00183 int SDFileSystem::initialise_card_v2() {
00184     for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
00185         wait_ms(50);
00186         _cmd58();
00187         _cmd(55, 0);
00188         if (_cmd(41, 0x40000000) == 0) {
00189             _cmd58();
00190             cdv = 1;
00191             return SDCARD_V2;
00192         }
00193     }
00194     
00195     return SDCARD_FAIL;
00196 }
00197 
00198 int SDFileSystem::disk_initialize() {
00199     int i = initialise_card();
00200     if(i==SDCARD_FAIL){
00201         return 1;
00202     }    
00203     _sectors = _sd_sectors();
00204     
00205     // Set block length to 512 (CMD16)
00206     if (_cmd(16, 512) != 0) {
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) {
00215     // set write address for single block (CMD24)
00216     if (_cmd(24, block_number * cdv) != 0) {
00217         return 1;
00218     }
00219     
00220     // send the data block
00221     _write(buffer, 512);
00222     return 0;
00223 }
00224 
00225 int SDFileSystem::disk_read(uint8_t *buffer, uint64_t block_number) {
00226     // set read address for single block (CMD17)
00227     if (_cmd(17, block_number * cdv) != 0) {
00228         return 1;
00229     }
00230     
00231     // receive the data
00232     _read(buffer, 512);
00233     return 0;
00234 }
00235 
00236 int SDFileSystem::disk_status() { return 0; }
00237 int SDFileSystem::disk_sync() { return 0; }
00238 uint64_t SDFileSystem::disk_sectors() { return _sectors; }
00239 
00240 
00241 // PRIVATE FUNCTIONS
00242 int SDFileSystem::_cmd(int cmd, int arg) {
00243     _cs = 0;
00244     
00245     // send a command
00246     _spi.write(0x40 | cmd);
00247     _spi.write(arg >> 24);
00248     _spi.write(arg >> 16);
00249     _spi.write(arg >> 8);
00250     _spi.write(arg >> 0);
00251     _spi.write(0x95);
00252     
00253     // wait for the repsonse (response[7] == 0)
00254     for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
00255         int response = _spi.write(0xFF);
00256         if (!(response & 0x80)) {
00257             _cs = 1;
00258             _spi.write(0xFF);
00259             return response;
00260         }
00261     }
00262     _cs = 1;
00263     _spi.write(0xFF);
00264     return -1; // timeout
00265 }
00266 int SDFileSystem::_cmdx(int cmd, int arg) {
00267     _cs = 0;
00268     
00269     // send a command
00270     _spi.write(0x40 | cmd);
00271     _spi.write(arg >> 24);
00272     _spi.write(arg >> 16);
00273     _spi.write(arg >> 8);
00274     _spi.write(arg >> 0);
00275     _spi.write(0x95);
00276     
00277     // wait for the repsonse (response[7] == 0)
00278     for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
00279         int response = _spi.write(0xFF);
00280         if (!(response & 0x80)) {
00281             return response;
00282         }
00283     }
00284     _cs = 1;
00285     _spi.write(0xFF);
00286     return -1; // timeout
00287 }
00288 
00289 
00290 int SDFileSystem::_cmd58() {
00291     _cs = 0;
00292     int arg = 0;
00293     
00294     // send a command
00295     _spi.write(0x40 | 58);
00296     _spi.write(arg >> 24);
00297     _spi.write(arg >> 16);
00298     _spi.write(arg >> 8);
00299     _spi.write(arg >> 0);
00300     _spi.write(0x95);
00301     
00302     // wait for the repsonse (response[7] == 0)
00303     for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
00304         int response = _spi.write(0xFF);
00305         if (!(response & 0x80)) {
00306             int ocr = _spi.write(0xFF) << 24;
00307             ocr |= _spi.write(0xFF) << 16;
00308             ocr |= _spi.write(0xFF) << 8;
00309             ocr |= _spi.write(0xFF) << 0;
00310             _cs = 1;
00311             _spi.write(0xFF);
00312             return response;
00313         }
00314     }
00315     _cs = 1;
00316     _spi.write(0xFF);
00317     return -1; // timeout
00318 }
00319 
00320 int SDFileSystem::_cmd8() {
00321     _cs = 0;
00322     
00323     // send a command
00324     _spi.write(0x40 | 8); // CMD8
00325     _spi.write(0x00);     // reserved
00326     _spi.write(0x00);     // reserved
00327     _spi.write(0x01);     // 3.3v
00328     _spi.write(0xAA);     // check pattern
00329     _spi.write(0x87);     // crc
00330     
00331     // wait for the repsonse (response[7] == 0)
00332     for (int i = 0; i < SD_COMMAND_TIMEOUT * 1000; i++) {
00333         char response[5];
00334         response[0] = _spi.write(0xFF);
00335         if (!(response[0] & 0x80)) {
00336             for (int j = 1; j < 5; j++) {
00337                 response[i] = _spi.write(0xFF);
00338             }
00339             _cs = 1;
00340             _spi.write(0xFF);
00341             return response[0];
00342         }
00343     }
00344     _cs = 1;
00345     _spi.write(0xFF);
00346     return -1; // timeout
00347 }
00348 
00349 int SDFileSystem::_read(uint8_t *buffer, uint32_t length) {
00350     _cs = 0;
00351     
00352     // read until start byte (0xFF)
00353     while (_spi.write(0xFF) != 0xFE);
00354     
00355     // read data
00356     for (uint32_t i = 0; i < length; i++) {
00357         buffer[i] = _spi.write(0xFF);
00358     }
00359     _spi.write(0xFF); // checksum
00360     _spi.write(0xFF);
00361     
00362     _cs = 1;
00363     _spi.write(0xFF);
00364     return 0;
00365 }
00366 
00367 int SDFileSystem::_write(const uint8_t*buffer, uint32_t length) {
00368     _cs = 0;
00369     
00370     // indicate start of block
00371     _spi.write(0xFE);
00372     
00373     // write the data
00374     for (uint32_t i = 0; i < length; i++) {
00375         _spi.write(buffer[i]);
00376     }
00377     
00378     // write the checksum
00379     _spi.write(0xFF);
00380     _spi.write(0xFF);
00381     
00382     // check the response token
00383     if ((_spi.write(0xFF) & 0x1F) != 0x05) {
00384         _cs = 1;
00385         _spi.write(0xFF);
00386         return 1;
00387     }
00388     
00389     // wait for write to finish
00390     while (_spi.write(0xFF) == 0);
00391     
00392     _cs = 1;
00393     _spi.write(0xFF);
00394     return 0;
00395 }
00396 
00397 static uint32_t ext_bits(unsigned char *data, int msb, int lsb) {
00398     uint32_t bits = 0;
00399     uint32_t size = 1 + msb - lsb;
00400     for (uint32_t i = 0; i < size; i++) {
00401         uint32_t position = lsb + i;
00402         uint32_t byte = 15 - (position >> 3);
00403         uint32_t bit = position & 0x7;
00404         uint32_t value = (data[byte] >> bit) & 1;
00405         bits |= value << i;
00406     }
00407     return bits;
00408 }
00409 
00410 uint64_t SDFileSystem::_sd_sectors() {
00411     uint32_t c_size, c_size_mult, read_bl_len;
00412     uint32_t block_len, mult, blocknr, capacity;
00413     uint32_t hc_c_size;
00414     uint64_t blocks;
00415     
00416     // CMD9, Response R2 (R1 byte + 16-byte block read)
00417     if (_cmdx(9, 0) != 0) {
00418         return 0;
00419     }
00420     
00421     uint8_t csd[16];
00422     if (_read(csd, 16) != 0) {
00423         return 0;
00424     }
00425     
00426     // csd_structure : csd[127:126]
00427     // c_size        : csd[73:62]
00428     // c_size_mult   : csd[49:47]
00429     // read_bl_len   : csd[83:80] - the *maximum* read block length
00430     
00431     int csd_structure = ext_bits(csd, 127, 126);
00432     
00433     switch (csd_structure) {
00434         case 0:
00435             cdv = 512;
00436             c_size = ext_bits(csd, 73, 62);
00437             c_size_mult = ext_bits(csd, 49, 47);
00438             read_bl_len = ext_bits(csd, 83, 80);
00439             
00440             block_len = 1 << read_bl_len;
00441             mult = 1 << (c_size_mult + 2);
00442             blocknr = (c_size + 1) * mult;
00443             capacity = blocknr * block_len;
00444             blocks = capacity / 512;
00445             break;
00446         
00447         case 1:
00448             cdv = 1;
00449             hc_c_size = ext_bits(csd, 63, 48);
00450             blocks = (hc_c_size+1)*1024;
00451             break;
00452         
00453         default:
00454             return 0;
00455     };
00456     return blocks;
00457 }