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