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