Luth Haroon / SD_modified
Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers USBMSD_SD.cpp Source File

USBMSD_SD.cpp

00001 /* mbed USBMSD_SD Library, for providing file access to SD cards
00002  * Copyright (c) 2008-2010, sford
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
00020  * THE 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 
00117 /*
00118 * Comment: Changes for SDHC support upto 32GB integrated into USBMSD_SD
00119 * Name:    KB USBMSD_SD by JF
00120 * Date:    07/24/2010 USBMSD_SD on 11 June 2012
00121 * Release: 0.1
00122 */
00123 
00124 #include "USBMSD_SD.h"
00125 
00126 #define SD_COMMAND_TIMEOUT 5000
00127 
00128 #define DEBUG
00129 
00130 USBMSD_SD::USBMSD_SD(PinName mosi, PinName miso, PinName sclk, PinName cs, PinName ncardpresent, PinName activity, PinName writeTest) :
00131         _spi(mosi, miso, sclk), _cs(cs), _ncardpresent(ncardpresent), _activity(activity), _writeTest(writeTest) {
00132     _ncardpresent.mode(PullDown);
00133     if (_ncardpresent) {
00134 #ifdef DEBUG
00135         printf("Please insert disk\n\r");
00136 #endif
00137         while (_ncardpresent) {
00138             _activity = 1;
00139             wait(.1);
00140             _activity = 0;
00141             wait(.1);
00142         }
00143         wait(1);
00144     }
00145     _cs = 1;
00146     _writeTest = 0;
00147     //no init
00148     _status = 0x01;
00149     connect();
00150 }
00151 
00152 #define R1_IDLE_STATE           (1 << 0)
00153 #define R1_ERASE_RESET          (1 << 1)
00154 #define R1_ILLEGAL_COMMAND      (1 << 2)
00155 #define R1_COM_CRC_ERROR        (1 << 3)
00156 #define R1_ERASE_SEQUENCE_ERROR (1 << 4)
00157 #define R1_ADDRESS_ERROR        (1 << 5)
00158 #define R1_PARAMETER_ERROR      (1 << 6)
00159 
00160 // Types
00161 //  - v1.x Standard Capacity
00162 //  - v2.x Standard Capacity
00163 //  - v2.x High Capacity
00164 //  - Not recognised as an SD Card
00165 
00166 #define SDCARD_FAIL 0
00167 #define SDCARD_V1   1
00168 #define SDCARD_V2   2
00169 #define SDCARD_V2HC 3
00170 
00171 int USBMSD_SD::initialise_card() {
00172     // Set to 100kHz for initialisation, and clock card with cs = 1
00173     _spi.frequency(100000);
00174     _cs = 1;
00175     for (int i=0; i<16; i++) {
00176         _spi.write(0xFF);
00177     }
00178 
00179     // send CMD0, should return with all zeros except IDLE STATE set (bit 0)
00180     if (_cmd(0, 0) != R1_IDLE_STATE) {
00181 #ifdef DEBUG
00182         printf("No disk, or could not put SD card in to SPI idle state\n\r");
00183 #endif
00184         NVIC_SystemReset();
00185         return SDCARD_FAIL; // This never gets ran, just added to override compiler warnings
00186     }
00187 
00188     // send CMD8 to determine whther it is ver 2.x
00189     int r = _cmd8();
00190     if (r == R1_IDLE_STATE) {
00191         return initialise_card_v2();
00192     } else if (r == (R1_IDLE_STATE | R1_ILLEGAL_COMMAND)) {
00193         return initialise_card_v1();
00194     } else {
00195 #ifdef DEBUG
00196         printf("Not in idle state after sending CMD8 (not an SD card?)\n\r");
00197 #endif
00198         NVIC_SystemReset();
00199         return SDCARD_FAIL; // This never gets ran, just added to override compiler warnings
00200     }
00201 }
00202 
00203 int USBMSD_SD::disk_present() {
00204     _ncardpresent.mode(PullDown);
00205     return (!_ncardpresent);
00206 }
00207 
00208 int USBMSD_SD::initialise_card_v1() {
00209     for (int i=0; i<SD_COMMAND_TIMEOUT; i++) {
00210         _cmd(55, 0);
00211         if (_cmd(41, 0) == 0) {
00212             cdv = 512;
00213 #ifdef DEBUG
00214             printf("\n\rInit: SEDCARD_V1\n\r");
00215 #endif
00216             return SDCARD_V1;
00217         }
00218     }
00219 
00220 #ifdef DEBUG
00221     printf("Timeout waiting for v1.x card\n\r");
00222 #endif
00223     NVIC_SystemReset();
00224     return SDCARD_FAIL; // This never gets ran, just added to override compiler warnings
00225 }
00226 
00227 int USBMSD_SD::initialise_card_v2() {
00228 
00229     for (int i=0; i<SD_COMMAND_TIMEOUT; i++) {
00230         wait_ms(50);
00231         _cmd58();
00232         _cmd(55, 0);
00233         if (_cmd(41, 0x40000000) == 0) {
00234             _cmd58();
00235 #ifdef DEBUG
00236             printf("\n\rInit: SDCARD_V2\n\r");
00237 #endif
00238             cdv = 1;
00239             return SDCARD_V2;
00240         }
00241     }
00242 
00243 #ifdef DEBUG
00244     printf("Timeout waiting for v2.x card\n\r");
00245 #endif
00246     NVIC_SystemReset();
00247     return SDCARD_FAIL; // This never gets ran, just added to override compiler warnings
00248 }
00249 
00250 int USBMSD_SD::disk_initialize() {
00251     int i = initialise_card();
00252 #ifdef DEBUG
00253     printf("init card = %d\n\r", i);
00254 #endif
00255     _sectors = _sd_sectors();
00256 
00257     // Set block length to 512 (CMD16)
00258     if (_cmd(16, 512) != 0) {
00259 #ifdef DEBUG
00260         printf("Set 512-byte block timed out\n\r");
00261 #endif
00262         NVIC_SystemReset();
00263     }
00264 
00265     _spi.frequency(4000000); // Set to 4MHz for data transfer
00266     // OK
00267     _status = 0x00;
00268     return 0;
00269 }
00270 
00271 int USBMSD_SD::disk_write(const char *buffer, int block_number) {
00272     // set write address for single block (CMD24)
00273     if (_cmd(24, block_number * cdv) != 0) {
00274         return 1;
00275     }
00276 
00277     // send the data block
00278     _write(buffer, 512);
00279     return 0;
00280 }
00281 
00282 int USBMSD_SD::disk_read(char *buffer, int block_number) {
00283     // set read address for single block (CMD17)
00284     if (_cmd(17, block_number * cdv) != 0) {
00285         return 1;
00286     }
00287 
00288     // receive the data
00289     _read(buffer, 512);
00290     return 0;
00291 }
00292 
00293 int USBMSD_SD::disk_status() {
00294     return _status;
00295 }
00296 int USBMSD_SD::disk_sync() {
00297     return 0;
00298 }
00299 int USBMSD_SD::disk_sectors() {
00300     return _sectors;
00301 }
00302 
00303 // PRIVATE FUNCTIONS
00304 
00305 int USBMSD_SD::_cmd(int cmd, int arg) {
00306     _cs = 0;
00307 
00308     // send a command
00309     _spi.write(0x40 | cmd);
00310     _spi.write(arg >> 24);
00311     _spi.write(arg >> 16);
00312     _spi.write(arg >> 8);
00313     _spi.write(arg >> 0);
00314     _spi.write(0x95);
00315 
00316     // wait for the repsonse (response[7] == 0)
00317     for (int i=0; i<SD_COMMAND_TIMEOUT; i++) {
00318         int response = _spi.write(0xFF);
00319         if (!(response & 0x80)) {
00320             _cs = 1;
00321             _spi.write(0xFF);
00322             return response;
00323         }
00324     }
00325     _cs = 1;
00326     _spi.write(0xFF);
00327     return -1; // timeout
00328 }
00329 int USBMSD_SD::_cmdx(int cmd, int arg) {
00330     _cs = 0;
00331 
00332     // send a command
00333     _spi.write(0x40 | cmd);
00334     _spi.write(arg >> 24);
00335     _spi.write(arg >> 16);
00336     _spi.write(arg >> 8);
00337     _spi.write(arg >> 0);
00338     _spi.write(0x95);
00339 
00340     // wait for the repsonse (response[7] == 0)
00341     for (int i=0; i<SD_COMMAND_TIMEOUT; i++) {
00342         int response = _spi.write(0xFF);
00343         if (!(response & 0x80)) {
00344             return response;
00345         }
00346     }
00347     _cs = 1;
00348     _spi.write(0xFF);
00349     return -1; // timeout
00350 }
00351 
00352 
00353 int USBMSD_SD::_cmd58() {
00354     _cs = 0;
00355     int arg = 0;
00356 
00357     // send a command
00358     _spi.write(0x40 | 58);
00359     _spi.write(arg >> 24);
00360     _spi.write(arg >> 16);
00361     _spi.write(arg >> 8);
00362     _spi.write(arg >> 0);
00363     _spi.write(0x95);
00364 
00365     // wait for the repsonse (response[7] == 0)
00366     for (int i=0; i<SD_COMMAND_TIMEOUT; i++) {
00367         int response = _spi.write(0xFF);
00368         if (!(response & 0x80)) {
00369             int ocr = _spi.write(0xFF) << 24;
00370             ocr |= _spi.write(0xFF) << 16;
00371             ocr |= _spi.write(0xFF) << 8;
00372             ocr |= _spi.write(0xFF) << 0;
00373 //            printf("OCR = 0x%08X\n", ocr);
00374             _cs = 1;
00375             _spi.write(0xFF);
00376             return response;
00377         }
00378     }
00379     _cs = 1;
00380     _spi.write(0xFF);
00381     return -1; // timeout
00382 }
00383 
00384 int USBMSD_SD::_cmd8() {
00385     _cs = 0;
00386 
00387     // send a command
00388     _spi.write(0x40 | 8); // CMD8
00389     _spi.write(0x00);     // reserved
00390     _spi.write(0x00);     // reserved
00391     _spi.write(0x01);     // 3.3v
00392     _spi.write(0xAA);     // check pattern
00393     _spi.write(0x87);     // crc
00394 
00395     // wait for the repsonse (response[7] == 0)
00396     for (int i=0; i<SD_COMMAND_TIMEOUT * 1000; i++) {
00397         char response[5];
00398         response[0] = _spi.write(0xFF);
00399         if (!(response[0] & 0x80)) {
00400             for (int j=1; j<5; j++) {
00401                 response[i] = _spi.write(0xFF);
00402             }
00403             _cs = 1;
00404             _spi.write(0xFF);
00405             return response[0];
00406         }
00407     }
00408     _cs = 1;
00409     _spi.write(0xFF);
00410     return -1; // timeout
00411 }
00412 
00413 int USBMSD_SD::_read(char *buffer, int length) {
00414     _cs = 0;
00415 
00416     // read until start byte (0xFF)
00417     while (_spi.write(0xFF) != 0xFE);
00418 
00419     // read data
00420     for (int i=0; i<length; i++) {
00421         _activity = 1;
00422         buffer[i] = _spi.write(0xFF);
00423         _activity = 0;
00424     }
00425     _spi.write(0xFF); // checksum
00426     _spi.write(0xFF);
00427 
00428     _cs = 1;
00429     _spi.write(0xFF);
00430     return 0;
00431 }
00432 
00433 int USBMSD_SD::_write(const char *buffer, int length) {
00434     //_writeTest = 1;
00435 
00436     _cs = 0;
00437 
00438     // indicate start of block
00439     _spi.write(0xFE);
00440 
00441     // write the data
00442     for (int i=0; i<length; i++) {
00443         _activity = 1;
00444         _spi.write(buffer[i]);
00445         _activity = 0;
00446     }
00447 
00448     // write the checksum
00449     _spi.write(0xFF);
00450     _spi.write(0xFF);
00451 
00452     // check the repsonse token
00453     if ((_spi.write(0xFF) & 0x1F) != 0x05) {
00454         _cs = 1;
00455         _spi.write(0xFF);
00456 #ifdef DEBUG
00457         printf("No response\n");
00458 #endif
00459         return 1;
00460     }
00461 
00462     // wait for write to finish
00463     while (_spi.write(0xFF) == 0);
00464 
00465     _cs = 1;
00466     _spi.write(0xFF);
00467     //_writeTest = 0;
00468     return 0;
00469 }
00470 
00471 static int ext_bits(char *data, int msb, int lsb) {
00472     int bits = 0;
00473     int size = 1 + msb - lsb;
00474     for (int i=0; i<size; i++) {
00475         int position = lsb + i;
00476         int byte = 15 - (position >> 3);
00477         int bit = position & 0x7;
00478         int value = (data[byte] >> bit) & 1;
00479         bits |= value << i;
00480     }
00481     return bits;
00482 }
00483 
00484 int USBMSD_SD::_sd_sectors() {
00485 
00486     int c_size, c_size_mult, read_bl_len;
00487     int block_len, mult, blocknr;
00488     int blocks;
00489 
00490     // CMD9, Response R2 (R1 byte + 16-byte block read)
00491     if (_cmdx(9, 0) != 0) {
00492 #ifdef DEBUG
00493         printf("Didn't get a response from the disk\n\r");
00494 #endif
00495         NVIC_SystemReset();
00496     }
00497 
00498     char csd[16];
00499     if (_read(csd, 16) != 0) {
00500 #ifdef DEBUG
00501         printf("Couldn't read csd response from disk\n\r");
00502 #endif
00503         NVIC_SystemReset();
00504     }
00505 
00506     // csd_structure : csd[127:126]
00507     // c_size        : csd[73:62]
00508     // c_size_mult   : csd[49:47]
00509     // read_bl_len   : csd[83:80] - the *maximum* read block length
00510 
00511     int csd_structure = ext_bits(csd, 127, 126);
00512 
00513 #ifdef DEBUG
00514     printf("\n\rCSD_STRUCT = %d\n\r", csd_structure);
00515 #endif
00516 
00517     switch (csd_structure) {
00518         case 0:
00519             cdv = 512;
00520             c_size = ext_bits(csd, 73, 62);
00521             c_size_mult = ext_bits(csd, 49, 47);
00522             read_bl_len = ext_bits(csd, 83, 80);
00523 
00524             block_len = 1 << read_bl_len;
00525             mult = 1 << (c_size_mult + 2);
00526             blocknr = (c_size + 1) * mult;
00527             capacity = blocknr * block_len;
00528             blocks = capacity / 512;
00529 #ifdef DEBUG
00530             printf("\n\rSDCard\n\rc_size: %.4X \n\rcapacity: %lld \n\rsectors: %d\n\r", c_size, capacity, blocks);
00531 #endif
00532             break;
00533 
00534         case 1:
00535             cdv = 1;
00536             c_size = ext_bits(csd, 63, 48);
00537             read_bl_len = ext_bits(csd, 83, 80);
00538             capacity = (c_size+1) * 1024;
00539             capacity = capacity * 512;
00540             blocks = (c_size+1)*1024;
00541 #ifdef DEBUG
00542             printf("\n\rSDHC Card \n\rhc_c_size: %.4X \n\rcapacity: %lld \n\rsectors: %d\n\r", c_size, capacity, blocks);
00543 #endif
00544             break;
00545 
00546         default:
00547 #ifdef DEBUG
00548             printf("This disk tastes funny! I only know about type 0 & 1 CSD structures\n\r");
00549 #endif
00550             NVIC_SystemReset();
00551     };
00552     return blocks;
00553 }
00554 
00555 uint64_t USBMSD_SD::disk_size() {
00556     return capacity;
00557 }