upload
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

SDFileSystem.cpp 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. /* mbed Microcontroller Library
  2. * Copyright (c) 2006-2012 ARM Limited
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. * SOFTWARE.
  21. */
  22. /* Introduction
  23. * ------------
  24. * SD and MMC cards support a number of interfaces, but common to them all
  25. * is one based on SPI. This is the one I'm implmenting because it means
  26. * it is much more portable even though not so performant, and we already
  27. * have the mbed SPI Interface!
  28. *
  29. * The main reference I'm using is Chapter 7, "SPI Mode" of:
  30. * http://www.sdcard.org/developers/tech/sdcard/pls/Simplified_Physical_Layer_Spec.pdf
  31. *
  32. * SPI Startup
  33. * -----------
  34. * The SD card powers up in SD mode. The SPI interface mode is selected by
  35. * asserting CS low and sending the reset command (CMD0). The card will
  36. * respond with a (R1) response.
  37. *
  38. * CMD8 is optionally sent to determine the voltage range supported, and
  39. * indirectly determine whether it is a version 1.x SD/non-SD card or
  40. * version 2.x. I'll just ignore this for now.
  41. *
  42. * ACMD41 is repeatedly issued to initialise the card, until "in idle"
  43. * (bit 0) of the R1 response goes to '0', indicating it is initialised.
  44. *
  45. * You should also indicate whether the host supports High Capicity cards,
  46. * and check whether the card is high capacity - i'll also ignore this
  47. *
  48. * SPI Protocol
  49. * ------------
  50. * The SD SPI protocol is based on transactions made up of 8-bit words, with
  51. * the host starting every bus transaction by asserting the CS signal low. The
  52. * card always responds to commands, data blocks and errors.
  53. *
  54. * The protocol supports a CRC, but by default it is off (except for the
  55. * first reset CMD0, where the CRC can just be pre-calculated, and CMD8)
  56. * I'll leave the CRC off I think!
  57. *
  58. * Standard capacity cards have variable data block sizes, whereas High
  59. * Capacity cards fix the size of data block to 512 bytes. I'll therefore
  60. * just always use the Standard Capacity cards with a block size of 512 bytes.
  61. * This is set with CMD16.
  62. *
  63. * You can read and write single blocks (CMD17, CMD25) or multiple blocks
  64. * (CMD18, CMD25). For simplicity, I'll just use single block accesses. When
  65. * the card gets a read command, it responds with a response token, and then
  66. * a data token or an error.
  67. *
  68. * SPI Command Format
  69. * ------------------
  70. * Commands are 6-bytes long, containing the command, 32-bit argument, and CRC.
  71. *
  72. * +---------------+------------+------------+-----------+----------+--------------+
  73. * | 01 | cmd[5:0] | arg[31:24] | arg[23:16] | arg[15:8] | arg[7:0] | crc[6:0] | 1 |
  74. * +---------------+------------+------------+-----------+----------+--------------+
  75. *
  76. * As I'm not using CRC, I can fix that byte to what is needed for CMD0 (0x95)
  77. *
  78. * All Application Specific commands shall be preceded with APP_CMD (CMD55).
  79. *
  80. * SPI Response Format
  81. * -------------------
  82. * The main response format (R1) is a status byte (normally zero). Key flags:
  83. * idle - 1 if the card is in an idle state/initialising
  84. * cmd - 1 if an illegal command code was detected
  85. *
  86. * +-------------------------------------------------+
  87. * R1 | 0 | arg | addr | seq | crc | cmd | erase | idle |
  88. * +-------------------------------------------------+
  89. *
  90. * R1b is the same, except it is followed by a busy signal (zeros) until
  91. * the first non-zero byte when it is ready again.
  92. *
  93. * Data Response Token
  94. * -------------------
  95. * Every data block written to the card is acknowledged by a byte
  96. * response token
  97. *
  98. * +----------------------+
  99. * | xxx | 0 | status | 1 |
  100. * +----------------------+
  101. * 010 - OK!
  102. * 101 - CRC Error
  103. * 110 - Write Error
  104. *
  105. * Single Block Read and Write
  106. * ---------------------------
  107. *
  108. * Block transfers have a byte header, followed by the data, followed
  109. * by a 16-bit CRC. In our case, the data will always be 512 bytes.
  110. *
  111. * +------+---------+---------+- - - -+---------+-----------+----------+
  112. * | 0xFE | data[0] | data[1] | | data[n] | crc[15:8] | crc[7:0] |
  113. * +------+---------+---------+- - - -+---------+-----------+----------+
  114. */
  115. #include "SDFileSystem.h"
  116. #include "mbed_debug.h"
  117. #define SD_COMMAND_TIMEOUT 5000
  118. #define SD_DBG 0
  119. SDFileSystem::SDFileSystem(PinName mosi, PinName miso, PinName sclk, PinName cs, const char* name) :
  120. FATFileSystem(name), _spi(mosi, miso, sclk), _cs(cs), _is_initialized(0) {
  121. _cs = 1;
  122. // Set default to 100kHz for initialisation and 1MHz for data transfer
  123. _init_sck = 100000;
  124. _transfer_sck = 1000000;
  125. }
  126. #define R1_IDLE_STATE (1 << 0)
  127. #define R1_ERASE_RESET (1 << 1)
  128. #define R1_ILLEGAL_COMMAND (1 << 2)
  129. #define R1_COM_CRC_ERROR (1 << 3)
  130. #define R1_ERASE_SEQUENCE_ERROR (1 << 4)
  131. #define R1_ADDRESS_ERROR (1 << 5)
  132. #define R1_PARAMETER_ERROR (1 << 6)
  133. // Types
  134. // - v1.x Standard Capacity
  135. // - v2.x Standard Capacity
  136. // - v2.x High Capacity
  137. // - Not recognised as an SD Card
  138. #define SDCARD_FAIL 0
  139. #define SDCARD_V1 1
  140. #define SDCARD_V2 2
  141. #define SDCARD_V2HC 3
  142. int SDFileSystem::initialise_card() {
  143. // Set to SCK for initialisation, and clock card with cs = 1
  144. _spi.frequency(_init_sck);
  145. _cs = 1;
  146. for (int i = 0; i < 16; i++) {
  147. _spi.write(0xFF);
  148. }
  149. // send CMD0, should return with all zeros except IDLE STATE set (bit 0)
  150. if (_cmd(0, 0) != R1_IDLE_STATE) {
  151. debug("No disk, or could not put SD card in to SPI idle state\n");
  152. return SDCARD_FAIL;
  153. }
  154. // send CMD8 to determine whther it is ver 2.x
  155. int r = _cmd8();
  156. if (r == R1_IDLE_STATE) {
  157. return initialise_card_v2();
  158. } else if (r == (R1_IDLE_STATE | R1_ILLEGAL_COMMAND)) {
  159. return initialise_card_v1();
  160. } else {
  161. debug("Not in idle state after sending CMD8 (not an SD card?)\n");
  162. return SDCARD_FAIL;
  163. }
  164. }
  165. int SDFileSystem::initialise_card_v1() {
  166. for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
  167. _cmd(55, 0);
  168. if (_cmd(41, 0) == 0) {
  169. cdv = 512;
  170. debug_if(SD_DBG, "\n\rInit: SEDCARD_V1\n\r");
  171. return SDCARD_V1;
  172. }
  173. }
  174. debug("Timeout waiting for v1.x card\n");
  175. return SDCARD_FAIL;
  176. }
  177. int SDFileSystem::initialise_card_v2() {
  178. for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
  179. wait_ms(50);
  180. _cmd58();
  181. _cmd(55, 0);
  182. if (_cmd(41, 0x40000000) == 0) {
  183. _cmd58();
  184. debug_if(SD_DBG, "\n\rInit: SDCARD_V2\n\r");
  185. cdv = 1;
  186. return SDCARD_V2;
  187. }
  188. }
  189. debug("Timeout waiting for v2.x card\n");
  190. return SDCARD_FAIL;
  191. }
  192. int SDFileSystem::disk_initialize() {
  193. _is_initialized = initialise_card();
  194. if (_is_initialized == 0) {
  195. debug("Fail to initialize card\n");
  196. return 1;
  197. }
  198. debug_if(SD_DBG, "init card = %d\n", _is_initialized);
  199. _sectors = _sd_sectors();
  200. // Set block length to 512 (CMD16)
  201. if (_cmd(16, 512) != 0) {
  202. debug("Set 512-byte block timed out\n");
  203. return 1;
  204. }
  205. // Set SCK for data transfer
  206. _spi.frequency(_transfer_sck);
  207. return 0;
  208. }
  209. int SDFileSystem::disk_write(const uint8_t* buffer, uint64_t block_number, uint8_t count) {
  210. if (!_is_initialized) {
  211. return -1;
  212. }
  213. for (uint64_t b = block_number; b < block_number + count; b++) {
  214. // set write address for single block (CMD24)
  215. if (_cmd(24, b * cdv) != 0) {
  216. return 1;
  217. }
  218. // send the data block
  219. _write(buffer, 512);
  220. buffer += 512;
  221. }
  222. return 0;
  223. }
  224. int SDFileSystem::disk_read(uint8_t* buffer, uint64_t block_number, uint8_t count) {
  225. if (!_is_initialized) {
  226. return -1;
  227. }
  228. for (uint64_t b = block_number; b < block_number + count; b++) {
  229. // set read address for single block (CMD17)
  230. if (_cmd(17, b * cdv) != 0) {
  231. return 1;
  232. }
  233. // receive the data
  234. _read(buffer, 512);
  235. buffer += 512;
  236. }
  237. return 0;
  238. }
  239. int SDFileSystem::disk_status() {
  240. // FATFileSystem::disk_status() returns 0 when initialized
  241. if (_is_initialized) {
  242. return 0;
  243. } else {
  244. return 1;
  245. }
  246. }
  247. int SDFileSystem::disk_sync() { return 0; }
  248. uint64_t SDFileSystem::disk_sectors() { return _sectors; }
  249. // PRIVATE FUNCTIONS
  250. int SDFileSystem::_cmd(int cmd, int arg) {
  251. _cs = 0;
  252. // send a command
  253. _spi.write(0x40 | cmd);
  254. _spi.write(arg >> 24);
  255. _spi.write(arg >> 16);
  256. _spi.write(arg >> 8);
  257. _spi.write(arg >> 0);
  258. _spi.write(0x95);
  259. // wait for the repsonse (response[7] == 0)
  260. for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
  261. int response = _spi.write(0xFF);
  262. if (!(response & 0x80)) {
  263. _cs = 1;
  264. _spi.write(0xFF);
  265. return response;
  266. }
  267. }
  268. _cs = 1;
  269. _spi.write(0xFF);
  270. return -1; // timeout
  271. }
  272. int SDFileSystem::_cmdx(int cmd, int arg) {
  273. _cs = 0;
  274. // send a command
  275. _spi.write(0x40 | cmd);
  276. _spi.write(arg >> 24);
  277. _spi.write(arg >> 16);
  278. _spi.write(arg >> 8);
  279. _spi.write(arg >> 0);
  280. _spi.write(0x95);
  281. // wait for the repsonse (response[7] == 0)
  282. for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
  283. int response = _spi.write(0xFF);
  284. if (!(response & 0x80)) {
  285. return response;
  286. }
  287. }
  288. _cs = 1;
  289. _spi.write(0xFF);
  290. return -1; // timeout
  291. }
  292. int SDFileSystem::_cmd58() {
  293. _cs = 0;
  294. int arg = 0;
  295. // send a command
  296. _spi.write(0x40 | 58);
  297. _spi.write(arg >> 24);
  298. _spi.write(arg >> 16);
  299. _spi.write(arg >> 8);
  300. _spi.write(arg >> 0);
  301. _spi.write(0x95);
  302. // wait for the repsonse (response[7] == 0)
  303. for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) {
  304. int response = _spi.write(0xFF);
  305. if (!(response & 0x80)) {
  306. int ocr = _spi.write(0xFF) << 24;
  307. ocr |= _spi.write(0xFF) << 16;
  308. ocr |= _spi.write(0xFF) << 8;
  309. ocr |= _spi.write(0xFF) << 0;
  310. _cs = 1;
  311. _spi.write(0xFF);
  312. return response;
  313. }
  314. }
  315. _cs = 1;
  316. _spi.write(0xFF);
  317. return -1; // timeout
  318. }
  319. int SDFileSystem::_cmd8() {
  320. _cs = 0;
  321. // send a command
  322. _spi.write(0x40 | 8); // CMD8
  323. _spi.write(0x00); // reserved
  324. _spi.write(0x00); // reserved
  325. _spi.write(0x01); // 3.3v
  326. _spi.write(0xAA); // check pattern
  327. _spi.write(0x87); // crc
  328. // wait for the repsonse (response[7] == 0)
  329. for (int i = 0; i < SD_COMMAND_TIMEOUT * 1000; i++) {
  330. char response[5];
  331. response[0] = _spi.write(0xFF);
  332. if (!(response[0] & 0x80)) {
  333. for (int j = 1; j < 5; j++) {
  334. response[i] = _spi.write(0xFF);
  335. }
  336. _cs = 1;
  337. _spi.write(0xFF);
  338. return response[0];
  339. }
  340. }
  341. _cs = 1;
  342. _spi.write(0xFF);
  343. return -1; // timeout
  344. }
  345. int SDFileSystem::_read(uint8_t *buffer, uint32_t length) {
  346. _cs = 0;
  347. // read until start byte (0xFF)
  348. while (_spi.write(0xFF) != 0xFE);
  349. // read data
  350. for (uint32_t i = 0; i < length; i++) {
  351. buffer[i] = _spi.write(0xFF);
  352. }
  353. _spi.write(0xFF); // checksum
  354. _spi.write(0xFF);
  355. _cs = 1;
  356. _spi.write(0xFF);
  357. return 0;
  358. }
  359. int SDFileSystem::_write(const uint8_t*buffer, uint32_t length) {
  360. _cs = 0;
  361. // indicate start of block
  362. _spi.write(0xFE);
  363. // write the data
  364. for (uint32_t i = 0; i < length; i++) {
  365. _spi.write(buffer[i]);
  366. }
  367. // write the checksum
  368. _spi.write(0xFF);
  369. _spi.write(0xFF);
  370. // check the response token
  371. if ((_spi.write(0xFF) & 0x1F) != 0x05) {
  372. _cs = 1;
  373. _spi.write(0xFF);
  374. return 1;
  375. }
  376. // wait for write to finish
  377. while (_spi.write(0xFF) == 0);
  378. _cs = 1;
  379. _spi.write(0xFF);
  380. return 0;
  381. }
  382. static uint32_t ext_bits(unsigned char *data, int msb, int lsb) {
  383. uint32_t bits = 0;
  384. uint32_t size = 1 + msb - lsb;
  385. for (uint32_t i = 0; i < size; i++) {
  386. uint32_t position = lsb + i;
  387. uint32_t byte = 15 - (position >> 3);
  388. uint32_t bit = position & 0x7;
  389. uint32_t value = (data[byte] >> bit) & 1;
  390. bits |= value << i;
  391. }
  392. return bits;
  393. }
  394. uint64_t SDFileSystem::_sd_sectors() {
  395. uint32_t c_size, c_size_mult, read_bl_len;
  396. uint32_t block_len, mult, blocknr, capacity;
  397. uint32_t hc_c_size;
  398. uint64_t blocks;
  399. // CMD9, Response R2 (R1 byte + 16-byte block read)
  400. if (_cmdx(9, 0) != 0) {
  401. debug("Didn't get a response from the disk\n");
  402. return 0;
  403. }
  404. uint8_t csd[16];
  405. if (_read(csd, 16) != 0) {
  406. debug("Couldn't read csd response from disk\n");
  407. return 0;
  408. }
  409. // csd_structure : csd[127:126]
  410. // c_size : csd[73:62]
  411. // c_size_mult : csd[49:47]
  412. // read_bl_len : csd[83:80] - the *maximum* read block length
  413. int csd_structure = ext_bits(csd, 127, 126);
  414. switch (csd_structure) {
  415. case 0:
  416. cdv = 512;
  417. c_size = ext_bits(csd, 73, 62);
  418. c_size_mult = ext_bits(csd, 49, 47);
  419. read_bl_len = ext_bits(csd, 83, 80);
  420. block_len = 1 << read_bl_len;
  421. mult = 1 << (c_size_mult + 2);
  422. blocknr = (c_size + 1) * mult;
  423. capacity = blocknr * block_len;
  424. blocks = capacity / 512;
  425. debug_if(SD_DBG, "\n\rSDCard\n\rc_size: %d \n\rcapacity: %ld \n\rsectors: %lld\n\r", c_size, capacity, blocks);
  426. break;
  427. case 1:
  428. cdv = 1;
  429. hc_c_size = ext_bits(csd, 63, 48);
  430. blocks = (hc_c_size+1)*1024;
  431. 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);
  432. break;
  433. default:
  434. debug("CSD struct unsupported\r\n");
  435. return 0;
  436. };
  437. return blocks;
  438. }