Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Dependents: SDFileSystem_HelloWorld Sharp_ce140f_emul
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 start-up procedure is complicated 00035 * by the requirement to support older SDCards in a backwards compatible 00036 * way with the new higher capacity variants SDHC and SDHC. 00037 * 00038 * The following figures from the specification with associated text describe 00039 * the SPI mode initialisation process: 00040 * - Figure 7-1: SD Memory Card State Diagram (SPI mode) 00041 * - Figure 7-2: SPI Mode Initialization Flow 00042 * 00043 * Firstly, a low initial clock should be selected (in the range of 100- 00044 * 400kHZ). After initialisation has been completed, the switch to a 00045 * higher clock speed can be made (e.g. 1MHz). Newer cards will support 00046 * higher speeds than the default _transfer_sck defined here. 00047 * 00048 * After power up, we need to provide at least 1 msec delay and 74 clock cycles 00049 * before sending any command to an SD Card. Since we get 8 clock cycles with each byte, 00050 * we can send 10 bytes for a total of 80 clock cycles. 00051 * The SDCard spec also specifies that CS must be held high during this period. 00052 * 00053 * Next, note the following from the SDCard specification (note to 00054 * Figure 7-1): 00055 * 00056 * In any of the cases CMD1 is not recommended because it may be difficult for the host 00057 * to distinguish between MultiMediaCard and SD Memory Card 00058 * 00059 * Hence CMD1 is not used for the initialisation sequence. 00060 * 00061 * The SPI interface mode is selected by asserting CS low and sending the 00062 * reset command (CMD0). The card will respond with a (R1) response. 00063 * In practice many cards initially respond with 0xff or invalid data 00064 * which is ignored. Data is read until a valid response is received 00065 * or the number of re-reads has exceeded a maximim count. If a valid 00066 * response is not received then the CMD0 can be retried. This 00067 * has been found to successfully initialise cards where the SPI master 00068 * (on MCU) has been reset but the SDCard has not, so the first 00069 * CMD0 may be lost. 00070 * 00071 * CMD8 is optionally sent to determine the voltage range supported, and 00072 * indirectly determine whether it is a version 1.x SD/non-SD card or 00073 * version 2.x. I'll just ignore this for now. 00074 * 00075 * ACMD41 is repeatedly issued to initialise the card, until "in idle" 00076 * (bit 0) of the R1 response goes to '0', indicating it is initialised. 00077 * 00078 * You should also indicate whether the host supports High Capicity cards, 00079 * and check whether the card is high capacity - i'll also ignore this 00080 * 00081 * SPI Protocol 00082 * ------------ 00083 * The SD SPI protocol is based on transactions made up of 8-bit words, with 00084 * the host starting every bus transaction by asserting the CS signal low. The 00085 * card always responds to commands, data blocks and errors. 00086 * 00087 * The protocol supports a CRC, but by default it is off (except for the 00088 * first reset CMD0, where the CRC can just be pre-calculated, and CMD8) 00089 * I'll leave the CRC off I think! 00090 * 00091 * Standard capacity cards have variable data block sizes, whereas High 00092 * Capacity cards fix the size of data block to 512 bytes. I'll therefore 00093 * just always use the Standard Capacity cards with a block size of 512 bytes. 00094 * This is set with CMD16. 00095 * 00096 * You can read and write single blocks (CMD17, CMD25) or multiple blocks 00097 * (CMD18, CMD25). For simplicity, I'll just use single block accesses. When 00098 * the card gets a read command, it responds with a response token, and then 00099 * a data token or an error. 00100 * 00101 * SPI Command Format 00102 * ------------------ 00103 * Commands are 6-bytes long, containing the command, 32-bit argument, and CRC. 00104 * 00105 * +---------------+------------+------------+-----------+----------+--------------+ 00106 * | 01 | cmd[5:0] | arg[31:24] | arg[23:16] | arg[15:8] | arg[7:0] | crc[6:0] | 1 | 00107 * +---------------+------------+------------+-----------+----------+--------------+ 00108 * 00109 * As I'm not using CRC, I can fix that byte to what is needed for CMD0 (0x95) 00110 * 00111 * All Application Specific commands shall be preceded with APP_CMD (CMD55). 00112 * 00113 * SPI Response Format 00114 * ------------------- 00115 * The main response format (R1) is a status byte (normally zero). Key flags: 00116 * idle - 1 if the card is in an idle state/initialising 00117 * cmd - 1 if an illegal command code was detected 00118 * 00119 * +-------------------------------------------------+ 00120 * R1 | 0 | arg | addr | seq | crc | cmd | erase | idle | 00121 * +-------------------------------------------------+ 00122 * 00123 * R1b is the same, except it is followed by a busy signal (zeros) until 00124 * the first non-zero byte when it is ready again. 00125 * 00126 * Data Response Token 00127 * ------------------- 00128 * Every data block written to the card is acknowledged by a byte 00129 * response token 00130 * 00131 * +----------------------+ 00132 * | xxx | 0 | status | 1 | 00133 * +----------------------+ 00134 * 010 - OK! 00135 * 101 - CRC Error 00136 * 110 - Write Error 00137 * 00138 * Single Block Read and Write 00139 * --------------------------- 00140 * 00141 * Block transfers have a byte header, followed by the data, followed 00142 * by a 16-bit CRC. In our case, the data will always be 512 bytes. 00143 * 00144 * +------+---------+---------+- - - -+---------+-----------+----------+ 00145 * | 0xFE | data[0] | data[1] | | data[n] | crc[15:8] | crc[7:0] | 00146 * +------+---------+---------+- - - -+---------+-----------+----------+ 00147 * 00148 * 00149 * 00150 */ 00151 #include "SDFileSystem.h" 00152 #include "mbed_debug.h" 00153 00154 #define SD_COMMAND_TIMEOUT 15/*5000*/ 00155 #define SD_CMD0_GO_IDLE_STATE_RETRIES 3 00156 #define SD_CMD0_GO_IDLE_STATE 0x00 00157 #define SD_DBG 0 00158 00159 SDFileSystem::SDFileSystem(PinName mosi, PinName miso, PinName sclk, PinName cs, const char* name) : 00160 FATFileSystem(name), _spi(mosi, miso, sclk), _cs(cs), _is_initialized(0) { 00161 _cs = 1; 00162 00163 // Set default frquency, for initialisation and data transfer 00164 _init_sck = 400000; 00165 _transfer_sck = 1000000; 00166 } 00167 00168 // R1 bits 00169 #define R1_IDLE_STATE (1 << 0) 00170 #define R1_ERASE_RESET (1 << 1) 00171 #define R1_ILLEGAL_COMMAND (1 << 2) 00172 #define R1_COM_CRC_ERROR (1 << 3) 00173 #define R1_ERASE_SEQUENCE_ERROR (1 << 4) 00174 #define R1_ADDRESS_ERROR (1 << 5) 00175 #define R1_PARAMETER_ERROR (1 << 6) 00176 00177 // Types 00178 // - v1.x Standard Capacity 00179 // - v2.x Standard Capacity 00180 // - v2.x High Capacity 00181 // - Not recognised as an SD Card 00182 #define SDCARD_FAIL 0 00183 #define SDCARD_V1 1 00184 #define SDCARD_V2 2 00185 #define SDCARD_V2HC 3 00186 00187 /* SDFileSystem::_go_idle_state() 00188 * 00189 * ARGUMENTS 00190 * None 00191 * DETAILS: 00192 * Put the SDCard into the SPI Mode idle state by sending the CMD0 00193 * (GO_IDLE_STATE) command. See the notes in the "SPI Startup" section 00194 * of the comments at the head of this file. 00195 * 00196 * RETURN: 00197 * -1 an error occured e.g. a valid response was not received. 00198 * R1_IDLE_STATE (0x1), the successful response from CMD0. 00199 */ 00200 int SDFileSystem::_go_idle_state() { 00201 _spi.lock(); 00202 00203 int cmd_arg = 0; /* CMD0 argument is just "stuff bits"*/ 00204 00205 /* Resetting the MCU SPI master may not reset the on-board SDCard, in which 00206 * case when MCU power-on occurs the SDCard will resume operations as 00207 * though there was no reset. In this scenario the first CMD0 will 00208 * not be interpretted as a command and get lost. For some cards retrying 00209 * the command overcomes this situation. */ 00210 for (int num_retries = 0; num_retries < SD_CMD0_GO_IDLE_STATE_RETRIES; num_retries++) { 00211 00212 // Set to SCK for initialisation, and clock card with CS high 00213 _cs = 1; 00214 // Initial delay 00215 wait_us (1000); 00216 // Initial 74 cycles required for few cards, before selecting SPI mode 00217 for (int i = 0; i < 16; i++) { 00218 _spi.write(0xFF); 00219 } 00220 00221 /* send a CMD0, with /CS asserted low */ 00222 _cs = 0; 00223 wait_us (1000); 00224 _spi.write(0x40 | SD_CMD0_GO_IDLE_STATE); 00225 _spi.write(cmd_arg >> 24); 00226 _spi.write(cmd_arg >> 16); 00227 _spi.write(cmd_arg >> 8); 00228 _spi.write(cmd_arg >> 0); 00229 _spi.write(0x95); 00230 00231 // wait for the response (response[7] == 0) 00232 for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) { 00233 int response = _spi.write(0xFF); 00234 /* Explicitly check for the R1_IDLE_STATE response rather that most significant bit 00235 * being 0 because invalid data can be returned. */ 00236 if (response != R1_IDLE_STATE) 00237 debug_if(SD_DBG, "CMD0 #%d (retry #%d) response: 0x%.2X\n", i, num_retries, response); 00238 else { 00239 _cs = 1; 00240 _spi.write(0xFF); 00241 _spi.unlock(); 00242 return response; 00243 } 00244 wait_us(1000); 00245 } 00246 } 00247 _cs = 1; 00248 _spi.write(0xFF); 00249 _spi.unlock(); 00250 return -1; // timeout 00251 } 00252 00253 int SDFileSystem::initialise_card() { 00254 00255 _spi.lock(); 00256 _spi.format(8, 0); 00257 _spi.frequency(_init_sck); 00258 _spi.unlock(); 00259 00260 /* moved within _go_idle_state 00261 _cs = 1; 00262 // Initial delay 00263 wait_us (1000); 00264 // Initial 74 cycles required for few cards, before selecting SPI mode 00265 for (int i = 0; i < 16; i++) { 00266 _spi.write(0xFF); 00267 } 00268 */ 00269 00270 /* Transition from SD Card mode to SPI mode by sending CMD0 GO_IDLE_STATE command */ 00271 if (_go_idle_state() != R1_IDLE_STATE) { 00272 debug_if(SD_DBG, "No disk, or could not put SD card in to SPI idle state\n"); 00273 return SDCARD_FAIL; 00274 } 00275 /* send CMD0, should return with all zeros except IDLE STATE set (bit 0) 00276 if (_cmd(0, 0) != R1_IDLE_STATE) { 00277 debug("No disk, or could not put SD card in to SPI idle state\n"); 00278 return SDCARD_FAIL; 00279 } 00280 */ 00281 00282 // send CMD8 to determine whther it is ver 2.x 00283 int r = _cmd8(); 00284 if (r == R1_IDLE_STATE) { 00285 return initialise_card_v2(); 00286 } else if (r == (R1_IDLE_STATE | R1_ILLEGAL_COMMAND)) { 00287 return initialise_card_v1(); 00288 } else { 00289 debug("Not in idle state after sending CMD8 (not an SD card?)\n"); 00290 return SDCARD_FAIL; 00291 } 00292 } 00293 00294 int SDFileSystem::initialise_card_v1() { 00295 for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) { 00296 _cmd(55, 0); 00297 if (_cmd(41, 0) == 0) { 00298 cdv = 512; 00299 debug_if(SD_DBG, "\n\rInit: SEDCARD_V1\n\r"); 00300 return SDCARD_V1; 00301 } 00302 } 00303 00304 debug("Timeout waiting for v1.x card\n"); 00305 return SDCARD_FAIL; 00306 } 00307 00308 int SDFileSystem::initialise_card_v2() { 00309 for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) { 00310 wait_ms(50); 00311 _cmd58(); 00312 _cmd(55, 0); 00313 if (_cmd(41, 0x40000000) == 0) { 00314 _cmd58(); 00315 debug_if(SD_DBG, "\n\rInit: SDCARD_V2\n\r"); 00316 cdv = 1; 00317 return SDCARD_V2; 00318 } 00319 } 00320 00321 debug("Timeout waiting for v2.x card\n"); 00322 return SDCARD_FAIL; 00323 } 00324 00325 int SDFileSystem::disk_initialize() { 00326 _is_initialized = initialise_card(); 00327 if (_is_initialized == 0) { 00328 debug("Fail to initialize card\n"); 00329 return 1; 00330 } 00331 debug_if(SD_DBG, "init card = %d\n", _is_initialized); 00332 _sectors = _sd_sectors(); 00333 00334 // Set block length to 512 (CMD16) 00335 if (_cmd(16, 512) != 0) { 00336 debug("Set 512-byte block timed out\n"); 00337 return 1; 00338 } 00339 00340 // Set SCK for data transfer 00341 _spi.frequency(_transfer_sck); 00342 return 0; 00343 } 00344 00345 int SDFileSystem::disk_write(const uint8_t* buffer, uint32_t block_number, uint32_t count) { 00346 if (!_is_initialized) { 00347 return -1; 00348 } 00349 00350 for (uint32_t b = block_number; b < block_number + count; b++) { 00351 // set write address for single block (CMD24) 00352 if (_cmd(24, b * cdv) != 0) { 00353 return 1; 00354 } 00355 00356 // send the data block 00357 _write(buffer, 512); 00358 buffer += 512; 00359 } 00360 00361 return 0; 00362 } 00363 00364 int SDFileSystem::disk_read(uint8_t* buffer, uint32_t block_number, uint32_t count) { 00365 if (!_is_initialized) { 00366 return -1; 00367 } 00368 00369 for (uint32_t b = block_number; b < block_number + count; b++) { 00370 // set read address for single block (CMD17) 00371 if (_cmd(17, b * cdv) != 0) { 00372 return 1; 00373 } 00374 00375 // receive the data 00376 _read(buffer, 512); 00377 buffer += 512; 00378 } 00379 00380 return 0; 00381 } 00382 00383 int SDFileSystem::disk_status() { 00384 // FATFileSystem::disk_status() returns 0 when initialized 00385 if (_is_initialized) { 00386 return 0; 00387 } else { 00388 return 1; 00389 } 00390 } 00391 00392 int SDFileSystem::disk_sync() { return 0; } 00393 uint32_t SDFileSystem::disk_sectors() { return _sectors; } 00394 00395 00396 // PRIVATE FUNCTIONS 00397 int SDFileSystem::_cmd(int cmd, int arg) { 00398 _cs = 0; 00399 00400 // send a command 00401 _spi.write(0x40 | cmd); 00402 _spi.write(arg >> 24); 00403 _spi.write(arg >> 16); 00404 _spi.write(arg >> 8); 00405 _spi.write(arg >> 0); 00406 _spi.write(0x95); 00407 00408 // wait for the repsonse (response[7] == 0) 00409 for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) { 00410 int response = _spi.write(0xFF); 00411 if (!(response & 0x80)) { 00412 _cs = 1; 00413 _spi.write(0xFF); 00414 return response; 00415 } 00416 } 00417 _cs = 1; 00418 _spi.write(0xFF); 00419 return -1; // timeout 00420 } 00421 int SDFileSystem::_cmdx(int cmd, int arg) { 00422 _cs = 0; 00423 00424 // send a command 00425 _spi.write(0x40 | cmd); 00426 _spi.write(arg >> 24); 00427 _spi.write(arg >> 16); 00428 _spi.write(arg >> 8); 00429 _spi.write(arg >> 0); 00430 _spi.write(0x95); 00431 00432 // wait for the repsonse (response[7] == 0) 00433 for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) { 00434 int response = _spi.write(0xFF); 00435 if (!(response & 0x80)) { 00436 return response; 00437 } 00438 } 00439 _cs = 1; 00440 _spi.write(0xFF); 00441 return -1; // timeout 00442 } 00443 00444 00445 int SDFileSystem::_cmd58() { 00446 _cs = 0; 00447 int arg = 0; 00448 00449 // send a command 00450 _spi.write(0x40 | 58); 00451 _spi.write(arg >> 24); 00452 _spi.write(arg >> 16); 00453 _spi.write(arg >> 8); 00454 _spi.write(arg >> 0); 00455 _spi.write(0x95); 00456 00457 // wait for the repsonse (response[7] == 0) 00458 for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) { 00459 int response = _spi.write(0xFF); 00460 if (!(response & 0x80)) { 00461 int ocr = _spi.write(0xFF) << 24; 00462 ocr |= _spi.write(0xFF) << 16; 00463 ocr |= _spi.write(0xFF) << 8; 00464 ocr |= _spi.write(0xFF) << 0; 00465 _cs = 1; 00466 _spi.write(0xFF); 00467 return response; 00468 } 00469 } 00470 _cs = 1; 00471 _spi.write(0xFF); 00472 return -1; // timeout 00473 } 00474 00475 int SDFileSystem::_cmd8() { 00476 _cs = 0; 00477 00478 // send a command 00479 _spi.write(0x40 | 8); // CMD8 00480 _spi.write(0x00); // reserved 00481 _spi.write(0x00); // reserved 00482 _spi.write(0x01); // 3.3v 00483 _spi.write(0xAA); // check pattern 00484 _spi.write(0x87); // crc 00485 00486 // wait for the repsonse (response[7] == 0) 00487 for (int i = 0; i < SD_COMMAND_TIMEOUT * 1000; i++) { 00488 char response[5]; 00489 response[0] = _spi.write(0xFF); 00490 if (!(response[0] & 0x80)) { 00491 for (int j = 1; j < 5; j++) { 00492 response[i] = _spi.write(0xFF); 00493 } 00494 _cs = 1; 00495 _spi.write(0xFF); 00496 return response[0]; 00497 } 00498 } 00499 _cs = 1; 00500 _spi.write(0xFF); 00501 return -1; // timeout 00502 } 00503 00504 int SDFileSystem::_read(uint8_t *buffer, uint32_t length) { 00505 _cs = 0; 00506 00507 // read until start byte (0xFF) 00508 while (_spi.write(0xFF) != 0xFE); 00509 00510 // read data 00511 for (uint32_t i = 0; i < length; i++) { 00512 buffer[i] = _spi.write(0xFF); 00513 } 00514 _spi.write(0xFF); // checksum 00515 _spi.write(0xFF); 00516 00517 _cs = 1; 00518 _spi.write(0xFF); 00519 return 0; 00520 } 00521 00522 int SDFileSystem::_write(const uint8_t*buffer, uint32_t length) { 00523 _cs = 0; 00524 00525 // indicate start of block 00526 _spi.write(0xFE); 00527 00528 // write the data 00529 for (uint32_t i = 0; i < length; i++) { 00530 _spi.write(buffer[i]); 00531 } 00532 00533 // write the checksum 00534 _spi.write(0xFF); 00535 _spi.write(0xFF); 00536 00537 // check the response token 00538 if ((_spi.write(0xFF) & 0x1F) != 0x05) { 00539 _cs = 1; 00540 _spi.write(0xFF); 00541 return 1; 00542 } 00543 00544 // wait for write to finish 00545 while (_spi.write(0xFF) == 0); 00546 00547 _cs = 1; 00548 _spi.write(0xFF); 00549 return 0; 00550 } 00551 00552 static uint32_t ext_bits(unsigned char *data, int msb, int lsb) { 00553 uint32_t bits = 0; 00554 uint32_t size = 1 + msb - lsb; 00555 for (uint32_t i = 0; i < size; i++) { 00556 uint32_t position = lsb + i; 00557 uint32_t byte = 15 - (position >> 3); 00558 uint32_t bit = position & 0x7; 00559 uint32_t value = (data[byte] >> bit) & 1; 00560 bits |= value << i; 00561 } 00562 return bits; 00563 } 00564 00565 uint32_t SDFileSystem::_sd_sectors() { 00566 uint32_t c_size, c_size_mult, read_bl_len; 00567 uint32_t block_len, mult, blocknr, capacity; 00568 uint32_t hc_c_size; 00569 uint32_t blocks; 00570 00571 // CMD9, Response R2 (R1 byte + 16-byte block read) 00572 if (_cmdx(9, 0) != 0) { 00573 debug("Didn't get a response from the disk\n"); 00574 return 0; 00575 } 00576 00577 uint8_t csd[16]; 00578 if (_read(csd, 16) != 0) { 00579 debug("Couldn't read csd response from disk\n"); 00580 return 0; 00581 } 00582 00583 // csd_structure : csd[127:126] 00584 // c_size : csd[73:62] 00585 // c_size_mult : csd[49:47] 00586 // read_bl_len : csd[83:80] - the *maximum* read block length 00587 00588 int csd_structure = ext_bits(csd, 127, 126); 00589 00590 switch (csd_structure) { 00591 case 0: 00592 cdv = 512; 00593 c_size = ext_bits(csd, 73, 62); 00594 c_size_mult = ext_bits(csd, 49, 47); 00595 read_bl_len = ext_bits(csd, 83, 80); 00596 00597 block_len = 1 << read_bl_len; 00598 mult = 1 << (c_size_mult + 2); 00599 blocknr = (c_size + 1) * mult; 00600 capacity = blocknr * block_len; 00601 blocks = capacity / 512; 00602 debug_if(SD_DBG, "\n\rSDCard\n\rc_size: %d \n\rcapacity: %ld \n\rsectors: %lld\n\r", c_size, capacity, blocks); 00603 break; 00604 00605 case 1: 00606 cdv = 1; 00607 hc_c_size = ext_bits(csd, 63, 48); 00608 blocks = (hc_c_size+1)*1024; 00609 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); 00610 break; 00611 00612 default: 00613 debug("CSD struct unsupported\r\n"); 00614 return 0; 00615 }; 00616 return blocks; 00617 }
Generated on Tue Jul 19 2022 13:49:42 by
