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.

Sd2Card.cpp 24KB

9 jaren geleden
9 jaren geleden
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  1. /* Arduino Sd2Card Library
  2. * Copyright (C) 2009 by William Greiman
  3. *
  4. * This file is part of the Arduino Sd2Card Library
  5. *
  6. * This Library is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This Library is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with the Arduino Sd2Card Library. If not, see
  18. * <http://www.gnu.org/licenses/>.
  19. */
  20. #include <Arduino.h>
  21. #include <SPI.h>
  22. #include "Sd2Card.h"
  23. #ifdef SPI_HAS_TRANSACTION
  24. static SPISettings settings;
  25. #endif
  26. #if defined(__MK20DX128__) || defined(__MK20DX256__)
  27. #define USE_TEENSY3_SPI
  28. // Teensy 3.0 functions (copied from sdfatlib20130629)
  29. #include <mk20dx128.h>
  30. // Limit initial fifo to three entries to avoid fifo overrun
  31. #define SPI_INITIAL_FIFO_DEPTH 3
  32. // define some symbols that are not in mk20dx128.h
  33. #ifndef SPI_SR_RXCTR
  34. #define SPI_SR_RXCTR 0XF0
  35. #endif // SPI_SR_RXCTR
  36. #ifndef SPI_PUSHR_CONT
  37. #define SPI_PUSHR_CONT 0X80000000
  38. #endif // SPI_PUSHR_CONT
  39. #ifndef SPI_PUSHR_CTAS
  40. #define SPI_PUSHR_CTAS(n) (((n) & 7) << 28)
  41. #endif // SPI_PUSHR_CTAS
  42. static void spiBegin() {
  43. SIM_SCGC6 |= SIM_SCGC6_SPI0;
  44. }
  45. static void spiInit(uint8_t spiRate) {
  46. switch (spiRate) {
  47. // the top 2 speeds are set to 24 MHz, for the SD library defaults
  48. case 0: settings = SPISettings(24000000, MSBFIRST, SPI_MODE0); break;
  49. case 1: settings = SPISettings(24000000, MSBFIRST, SPI_MODE0); break;
  50. case 2: settings = SPISettings(8000000, MSBFIRST, SPI_MODE0); break;
  51. case 3: settings = SPISettings(4000000, MSBFIRST, SPI_MODE0); break;
  52. case 4: settings = SPISettings(3000000, MSBFIRST, SPI_MODE0); break;
  53. case 5: settings = SPISettings(2000000, MSBFIRST, SPI_MODE0); break;
  54. default: settings = SPISettings(400000, MSBFIRST, SPI_MODE0);
  55. }
  56. SPI.begin();
  57. }
  58. /** SPI receive a byte */
  59. static uint8_t spiRec() {
  60. SPI0_MCR |= SPI_MCR_CLR_RXF;
  61. SPI0_SR = SPI_SR_TCF;
  62. SPI0_PUSHR = 0xFF;
  63. while (!(SPI0_SR & SPI_SR_TCF)) {}
  64. return SPI0_POPR;
  65. }
  66. /** SPI receive multiple bytes */
  67. static uint8_t spiRec(uint8_t* buf, size_t len) {
  68. // clear any data in RX FIFO
  69. SPI0_MCR = SPI_MCR_MSTR | SPI_MCR_CLR_RXF | SPI_MCR_PCSIS(0x1F);
  70. // use 16 bit frame to avoid TD delay between frames
  71. // get one byte if len is odd
  72. if (len & 1) {
  73. *buf++ = spiRec();
  74. len--;
  75. }
  76. // initial number of words to push into TX FIFO
  77. int nf = len/2 < SPI_INITIAL_FIFO_DEPTH ? len/2 : SPI_INITIAL_FIFO_DEPTH;
  78. for (int i = 0; i < nf; i++) {
  79. SPI0_PUSHR = SPI_PUSHR_CONT | SPI_PUSHR_CTAS(1) | 0XFFFF;
  80. }
  81. uint8_t* limit = buf + len - 2*nf;
  82. while (buf < limit) {
  83. while (!(SPI0_SR & SPI_SR_RXCTR)) {}
  84. SPI0_PUSHR = SPI_PUSHR_CONT | SPI_PUSHR_CTAS(1) | 0XFFFF;
  85. uint16_t w = SPI0_POPR;
  86. *buf++ = w >> 8;
  87. *buf++ = w & 0XFF;
  88. }
  89. // limit for rest of RX data
  90. limit += 2*nf;
  91. while (buf < limit) {
  92. while (!(SPI0_SR & SPI_SR_RXCTR)) {}
  93. uint16_t w = SPI0_POPR;
  94. *buf++ = w >> 8;
  95. *buf++ = w & 0XFF;
  96. }
  97. return 0;
  98. }
  99. static void spiRecIgnore(size_t len) {
  100. // clear any data in RX FIFO
  101. SPI0_MCR = SPI_MCR_MSTR | SPI_MCR_CLR_RXF | SPI_MCR_PCSIS(0x1F);
  102. // use 16 bit frame to avoid TD delay between frames
  103. // get one byte if len is odd
  104. if (len & 1) {
  105. spiRec();
  106. len--;
  107. }
  108. // initial number of words to push into TX FIFO
  109. int nf = len/2 < SPI_INITIAL_FIFO_DEPTH ? len/2 : SPI_INITIAL_FIFO_DEPTH;
  110. for (int i = 0; i < nf; i++) {
  111. SPI0_PUSHR = SPI_PUSHR_CONT | SPI_PUSHR_CTAS(1) | 0XFFFF;
  112. len -= 2;
  113. }
  114. //uint8_t* limit = buf + len - 2*nf;
  115. //while (buf < limit) {
  116. while (len > 0) {
  117. while (!(SPI0_SR & SPI_SR_RXCTR)) {}
  118. SPI0_PUSHR = SPI_PUSHR_CONT | SPI_PUSHR_CTAS(1) | 0XFFFF;
  119. SPI0_POPR;
  120. len -= 2;
  121. }
  122. // limit for rest of RX data
  123. while (nf > 0) {
  124. while (!(SPI0_SR & SPI_SR_RXCTR)) {}
  125. SPI0_POPR;
  126. nf--;
  127. }
  128. }
  129. /** SPI send a byte */
  130. static void spiSend(uint8_t b) {
  131. SPI0_MCR |= SPI_MCR_CLR_RXF;
  132. SPI0_SR = SPI_SR_TCF;
  133. SPI0_PUSHR = b;
  134. while (!(SPI0_SR & SPI_SR_TCF)) {}
  135. }
  136. /** SPI send multiple bytes */
  137. #if 0
  138. static void spiSend(const uint8_t* output, size_t len) {
  139. // clear any data in RX FIFO
  140. SPI0_MCR = SPI_MCR_MSTR | SPI_MCR_CLR_RXF | SPI_MCR_PCSIS(0x1F);
  141. // use 16 bit frame to avoid TD delay between frames
  142. // send one byte if len is odd
  143. if (len & 1) {
  144. spiSend(*output++);
  145. len--;
  146. }
  147. // initial number of words to push into TX FIFO
  148. int nf = len/2 < SPI_INITIAL_FIFO_DEPTH ? len/2 : SPI_INITIAL_FIFO_DEPTH;
  149. // limit for pushing data into TX fifo
  150. const uint8_t* limit = output + len;
  151. for (int i = 0; i < nf; i++) {
  152. uint16_t w = (*output++) << 8;
  153. w |= *output++;
  154. SPI0_PUSHR = SPI_PUSHR_CONT | SPI_PUSHR_CTAS(1) | w;
  155. }
  156. // write data to TX FIFO
  157. while (output < limit) {
  158. uint16_t w = *output++ << 8;
  159. w |= *output++;
  160. while (!(SPI0_SR & SPI_SR_RXCTR)) {}
  161. SPI0_PUSHR = SPI_PUSHR_CONT | SPI_PUSHR_CTAS(1) | w;
  162. SPI0_POPR;
  163. }
  164. // wait for data to be sent
  165. while (nf) {
  166. while (!(SPI0_SR & SPI_SR_RXCTR)) {}
  167. SPI0_POPR;
  168. nf--;
  169. }
  170. }
  171. #endif
  172. //------------------------------------------------------------------------------
  173. #else
  174. // functions for hardware SPI
  175. /** Send a byte to the card */
  176. static void spiSend(uint8_t b) {
  177. SPDR = b;
  178. while (!(SPSR & (1 << SPIF)));
  179. }
  180. /** Receive a byte from the card */
  181. static uint8_t spiRec(void) {
  182. spiSend(0XFF);
  183. return SPDR;
  184. }
  185. #endif
  186. //------------------------------------------------------------------------------
  187. // send command and return error code. Return zero for OK
  188. uint8_t Sd2Card::cardCommand(uint8_t cmd, uint32_t arg) {
  189. // end read if in partialBlockRead mode
  190. readEnd();
  191. // select card
  192. chipSelectLow();
  193. // wait up to 300 ms if busy
  194. waitNotBusy(300);
  195. // send command
  196. spiSend(cmd | 0x40);
  197. // send argument
  198. for (int8_t s = 24; s >= 0; s -= 8) spiSend(arg >> s);
  199. // send CRC
  200. uint8_t crc = 0XFF;
  201. if (cmd == CMD0) crc = 0X95; // correct crc for CMD0 with arg 0
  202. if (cmd == CMD8) crc = 0X87; // correct crc for CMD8 with arg 0X1AA
  203. spiSend(crc);
  204. // wait for response
  205. for (uint8_t i = 0; ((status_ = spiRec()) & 0X80) && i != 0XFF; i++);
  206. return status_;
  207. }
  208. //------------------------------------------------------------------------------
  209. /**
  210. * Determine the size of an SD flash memory card.
  211. *
  212. * \return The number of 512 byte data blocks in the card
  213. * or zero if an error occurs.
  214. */
  215. uint32_t Sd2Card::cardSize(void) {
  216. csd_t csd;
  217. if (!readCSD(&csd)) return 0;
  218. if (csd.v1.csd_ver == 0) {
  219. uint8_t read_bl_len = csd.v1.read_bl_len;
  220. uint16_t c_size = (csd.v1.c_size_high << 10)
  221. | (csd.v1.c_size_mid << 2) | csd.v1.c_size_low;
  222. uint8_t c_size_mult = (csd.v1.c_size_mult_high << 1)
  223. | csd.v1.c_size_mult_low;
  224. return (uint32_t)(c_size + 1) << (c_size_mult + read_bl_len - 7);
  225. } else if (csd.v2.csd_ver == 1) {
  226. uint32_t c_size = ((uint32_t)csd.v2.c_size_high << 16)
  227. | (csd.v2.c_size_mid << 8) | csd.v2.c_size_low;
  228. return (c_size + 1) << 10;
  229. } else {
  230. error(SD_CARD_ERROR_BAD_CSD);
  231. return 0;
  232. }
  233. }
  234. //------------------------------------------------------------------------------
  235. #ifdef SPI_HAS_TRANSACTION
  236. static uint8_t chip_select_asserted = 0;
  237. #endif
  238. void Sd2Card::chipSelectHigh(void) {
  239. digitalWrite(chipSelectPin_, HIGH);
  240. #ifdef SPI_HAS_TRANSACTION
  241. if (chip_select_asserted) {
  242. chip_select_asserted = 0;
  243. SPI.endTransaction();
  244. }
  245. #endif
  246. }
  247. //------------------------------------------------------------------------------
  248. void Sd2Card::chipSelectLow(void) {
  249. #ifdef SPI_HAS_TRANSACTION
  250. if (!chip_select_asserted) {
  251. chip_select_asserted = 1;
  252. SPI.beginTransaction(settings);
  253. }
  254. #endif
  255. digitalWrite(chipSelectPin_, LOW);
  256. }
  257. //------------------------------------------------------------------------------
  258. /** Erase a range of blocks.
  259. *
  260. * \param[in] firstBlock The address of the first block in the range.
  261. * \param[in] lastBlock The address of the last block in the range.
  262. *
  263. * \note This function requests the SD card to do a flash erase for a
  264. * range of blocks. The data on the card after an erase operation is
  265. * either 0 or 1, depends on the card vendor. The card must support
  266. * single block erase.
  267. *
  268. * \return The value one, true, is returned for success and
  269. * the value zero, false, is returned for failure.
  270. */
  271. uint8_t Sd2Card::erase(uint32_t firstBlock, uint32_t lastBlock) {
  272. if (!eraseSingleBlockEnable()) {
  273. error(SD_CARD_ERROR_ERASE_SINGLE_BLOCK);
  274. goto fail;
  275. }
  276. if (type_ != SD_CARD_TYPE_SDHC) {
  277. firstBlock <<= 9;
  278. lastBlock <<= 9;
  279. }
  280. if (cardCommand(CMD32, firstBlock)
  281. || cardCommand(CMD33, lastBlock)
  282. || cardCommand(CMD38, 0)) {
  283. error(SD_CARD_ERROR_ERASE);
  284. goto fail;
  285. }
  286. if (!waitNotBusy(SD_ERASE_TIMEOUT)) {
  287. error(SD_CARD_ERROR_ERASE_TIMEOUT);
  288. goto fail;
  289. }
  290. chipSelectHigh();
  291. return true;
  292. fail:
  293. chipSelectHigh();
  294. return false;
  295. }
  296. //------------------------------------------------------------------------------
  297. /** Determine if card supports single block erase.
  298. *
  299. * \return The value one, true, is returned if single block erase is supported.
  300. * The value zero, false, is returned if single block erase is not supported.
  301. */
  302. uint8_t Sd2Card::eraseSingleBlockEnable(void) {
  303. csd_t csd;
  304. return readCSD(&csd) ? csd.v1.erase_blk_en : 0;
  305. }
  306. //------------------------------------------------------------------------------
  307. /**
  308. * Initialize an SD flash memory card.
  309. *
  310. * \param[in] sckRateID SPI clock rate selector. See setSckRate().
  311. * \param[in] chipSelectPin SD chip select pin number.
  312. *
  313. * \return The value one, true, is returned for success and
  314. * the value zero, false, is returned for failure. The reason for failure
  315. * can be determined by calling errorCode() and errorData().
  316. */
  317. uint8_t Sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin) {
  318. errorCode_ = inBlock_ = partialBlockRead_ = type_ = 0;
  319. chipSelectPin_ = chipSelectPin;
  320. // 16-bit init start time allows over a minute
  321. uint16_t t0 = (uint16_t)millis();
  322. uint32_t arg;
  323. digitalWrite(chipSelectPin_, HIGH);
  324. pinMode(chipSelectPin_, OUTPUT);
  325. digitalWrite(chipSelectPin_, HIGH);
  326. #ifdef USE_TEENSY3_SPI
  327. spiBegin();
  328. spiInit(6);
  329. #else
  330. // set pin modes
  331. pinMode(SPI_MISO_PIN, INPUT);
  332. pinMode(SPI_MOSI_PIN, OUTPUT);
  333. pinMode(SPI_SCK_PIN, OUTPUT);
  334. // SS must be in output mode even it is not chip select
  335. pinMode(SS_PIN, OUTPUT);
  336. digitalWrite(SS_PIN, HIGH); // disable any SPI device using hardware SS pin
  337. // Enable SPI, Master, clock rate f_osc/128
  338. SPCR = (1 << SPE) | (1 << MSTR) | (1 << SPR1) | (1 << SPR0);
  339. // clear double speed
  340. SPSR &= ~(1 << SPI2X);
  341. #ifdef SPI_HAS_TRANSACTION
  342. settings = SPISettings(250000, MSBFIRST, SPI_MODE0);
  343. #endif
  344. #endif // not USE_TEENSY3_SPI
  345. // must supply min of 74 clock cycles with CS high.
  346. #ifdef SPI_HAS_TRANSACTION
  347. SPI.beginTransaction(settings);
  348. #endif
  349. for (uint8_t i = 0; i < 10; i++) spiSend(0XFF);
  350. #ifdef SPI_HAS_TRANSACTION
  351. SPI.endTransaction();
  352. #endif
  353. chipSelectLow();
  354. // command to go idle in SPI mode
  355. while ((status_ = cardCommand(CMD0, 0)) != R1_IDLE_STATE) {
  356. if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) {
  357. error(SD_CARD_ERROR_CMD0);
  358. goto fail;
  359. }
  360. }
  361. // check SD version
  362. if ((cardCommand(CMD8, 0x1AA) & R1_ILLEGAL_COMMAND)) {
  363. type(SD_CARD_TYPE_SD1);
  364. } else {
  365. // only need last byte of r7 response
  366. for (uint8_t i = 0; i < 4; i++) status_ = spiRec();
  367. if (status_ != 0XAA) {
  368. error(SD_CARD_ERROR_CMD8);
  369. goto fail;
  370. }
  371. type(SD_CARD_TYPE_SD2);
  372. }
  373. // initialize card and send host supports SDHC if SD2
  374. arg = type() == SD_CARD_TYPE_SD2 ? 0X40000000 : 0;
  375. while ((status_ = cardAcmd(ACMD41, arg)) != R1_READY_STATE) {
  376. // check for timeout
  377. if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) {
  378. error(SD_CARD_ERROR_ACMD41);
  379. goto fail;
  380. }
  381. }
  382. // if SD2 read OCR register to check for SDHC card
  383. if (type() == SD_CARD_TYPE_SD2) {
  384. if (cardCommand(CMD58, 0)) {
  385. error(SD_CARD_ERROR_CMD58);
  386. goto fail;
  387. }
  388. if ((spiRec() & 0XC0) == 0XC0) type(SD_CARD_TYPE_SDHC);
  389. // discard rest of ocr - contains allowed voltage range
  390. for (uint8_t i = 0; i < 3; i++) spiRec();
  391. }
  392. chipSelectHigh();
  393. return setSckRate(sckRateID);
  394. fail:
  395. chipSelectHigh();
  396. return false;
  397. }
  398. //------------------------------------------------------------------------------
  399. /**
  400. * Enable or disable partial block reads.
  401. *
  402. * Enabling partial block reads improves performance by allowing a block
  403. * to be read over the SPI bus as several sub-blocks. Errors may occur
  404. * if the time between reads is too long since the SD card may timeout.
  405. * The SPI SS line will be held low until the entire block is read or
  406. * readEnd() is called.
  407. *
  408. * Use this for applications like the Adafruit Wave Shield.
  409. *
  410. * \param[in] value The value TRUE (non-zero) or FALSE (zero).)
  411. */
  412. void Sd2Card::partialBlockRead(uint8_t value) {
  413. readEnd();
  414. partialBlockRead_ = value;
  415. }
  416. //------------------------------------------------------------------------------
  417. /**
  418. * Read a 512 byte block from an SD card device.
  419. *
  420. * \param[in] block Logical block to be read.
  421. * \param[out] dst Pointer to the location that will receive the data.
  422. * \return The value one, true, is returned for success and
  423. * the value zero, false, is returned for failure.
  424. */
  425. uint8_t Sd2Card::readBlock(uint32_t block, uint8_t* dst) {
  426. return readData(block, 0, 512, dst);
  427. }
  428. //------------------------------------------------------------------------------
  429. /**
  430. * Read part of a 512 byte block from an SD card.
  431. *
  432. * \param[in] block Logical block to be read.
  433. * \param[in] offset Number of bytes to skip at start of block
  434. * \param[out] dst Pointer to the location that will receive the data.
  435. * \param[in] count Number of bytes to read
  436. * \return The value one, true, is returned for success and
  437. * the value zero, false, is returned for failure.
  438. */
  439. uint8_t Sd2Card::readData(uint32_t block,
  440. uint16_t offset, uint16_t count, uint8_t* dst) {
  441. #if !defined(USE_TEENSY3_SPI) && defined(OPTIMIZE_HARDWARE_SPI)
  442. uint16_t n;
  443. #endif
  444. if (count == 0) return true;
  445. if ((count + offset) > 512) {
  446. goto fail;
  447. }
  448. if (!inBlock_ || block != block_ || offset < offset_) {
  449. block_ = block;
  450. // use address if not SDHC card
  451. if (type()!= SD_CARD_TYPE_SDHC) block <<= 9;
  452. if (cardCommand(CMD17, block)) {
  453. error(SD_CARD_ERROR_CMD17);
  454. goto fail;
  455. }
  456. if (!waitStartBlock()) {
  457. goto fail;
  458. }
  459. offset_ = 0;
  460. inBlock_ = 1;
  461. }
  462. #if defined(USE_TEENSY3_SPI)
  463. // skip data before offset
  464. //for (;offset_ < offset; offset_++) {
  465. //spiRec();
  466. //}
  467. spiRecIgnore(offset);
  468. spiRec(dst, count);
  469. #elif defined(OPTIMIZE_HARDWARE_SPI)
  470. // start first spi transfer
  471. SPDR = 0XFF;
  472. // skip data before offset
  473. for (;offset_ < offset; offset_++) {
  474. while (!(SPSR & (1 << SPIF)));
  475. SPDR = 0XFF;
  476. }
  477. // transfer data
  478. n = count - 1;
  479. for (uint16_t i = 0; i < n; i++) {
  480. while (!(SPSR & (1 << SPIF)));
  481. dst[i] = SPDR;
  482. SPDR = 0XFF;
  483. }
  484. // wait for last byte
  485. while (!(SPSR & (1 << SPIF)));
  486. dst[n] = SPDR;
  487. #else // OPTIMIZE_HARDWARE_SPI
  488. // skip data before offset
  489. for (;offset_ < offset; offset_++) {
  490. spiRec();
  491. }
  492. // transfer data
  493. for (uint16_t i = 0; i < count; i++) {
  494. dst[i] = spiRec();
  495. }
  496. #endif // OPTIMIZE_HARDWARE_SPI
  497. offset_ += count;
  498. if (!partialBlockRead_ || offset_ >= 512) {
  499. // read rest of data, checksum and set chip select high
  500. readEnd();
  501. }
  502. return true;
  503. fail:
  504. chipSelectHigh();
  505. return false;
  506. }
  507. //------------------------------------------------------------------------------
  508. /** Skip remaining data in a block when in partial block read mode. */
  509. void Sd2Card::readEnd(void) {
  510. if (inBlock_) {
  511. // skip data and crc
  512. #if defined(USE_TEENSY3_SPI)
  513. if (offset_ < 514) {
  514. spiRecIgnore(514 - offset_);
  515. offset_ = 514;
  516. }
  517. #elif defined(OPTIMIZE_HARDWARE_SPI)
  518. // optimize skip for hardware
  519. SPDR = 0XFF;
  520. while (offset_++ < 513) {
  521. while (!(SPSR & (1 << SPIF)));
  522. SPDR = 0XFF;
  523. }
  524. // wait for last crc byte
  525. while (!(SPSR & (1 << SPIF)));
  526. #else // OPTIMIZE_HARDWARE_SPI
  527. while (offset_++ < 514) spiRec();
  528. #endif // OPTIMIZE_HARDWARE_SPI
  529. chipSelectHigh();
  530. inBlock_ = 0;
  531. }
  532. }
  533. //------------------------------------------------------------------------------
  534. /** read CID or CSR register */
  535. uint8_t Sd2Card::readRegister(uint8_t cmd, void* buf) {
  536. uint8_t* dst = reinterpret_cast<uint8_t*>(buf);
  537. if (cardCommand(cmd, 0)) {
  538. error(SD_CARD_ERROR_READ_REG);
  539. goto fail;
  540. }
  541. if (!waitStartBlock()) goto fail;
  542. // transfer data
  543. for (uint16_t i = 0; i < 16; i++) dst[i] = spiRec();
  544. spiRec(); // get first crc byte
  545. spiRec(); // get second crc byte
  546. chipSelectHigh();
  547. return true;
  548. fail:
  549. chipSelectHigh();
  550. return false;
  551. }
  552. //------------------------------------------------------------------------------
  553. /**
  554. * Set the SPI clock rate.
  555. *
  556. * \param[in] sckRateID A value in the range [0, 6].
  557. *
  558. * 0 = 8 MHz
  559. * 1 = 4 MHz
  560. * 2 = 2 MHz
  561. * 3 = 1 MHz
  562. * 4 = 500 kHz
  563. * 5 = 125 kHz
  564. * 6 = 63 kHz
  565. *
  566. * The SPI clock will be set to F_CPU/pow(2, 1 + sckRateID). The maximum
  567. * SPI rate is F_CPU/2 for \a sckRateID = 0 and the minimum rate is F_CPU/128
  568. * for \a scsRateID = 6.
  569. *
  570. * \return The value one, true, is returned for success and the value zero,
  571. * false, is returned for an invalid value of \a sckRateID.
  572. */
  573. uint8_t Sd2Card::setSckRate(uint8_t sckRateID) {
  574. #ifdef USE_TEENSY3_SPI
  575. spiInit(sckRateID);
  576. return true;
  577. #else
  578. if (sckRateID > 6) sckRateID = 6;
  579. // see avr processor datasheet for SPI register bit definitions
  580. if ((sckRateID & 1) || sckRateID == 6) {
  581. SPSR &= ~(1 << SPI2X);
  582. } else {
  583. SPSR |= (1 << SPI2X);
  584. }
  585. SPCR &= ~((1 <<SPR1) | (1 << SPR0));
  586. SPCR |= (sckRateID & 4 ? (1 << SPR1) : 0)
  587. | (sckRateID & 2 ? (1 << SPR0) : 0);
  588. #ifdef SPI_HAS_TRANSACTION
  589. switch (sckRateID) {
  590. case 0: settings = SPISettings(8000000, MSBFIRST, SPI_MODE0); break;
  591. case 1: settings = SPISettings(4000000, MSBFIRST, SPI_MODE0); break;
  592. case 2: settings = SPISettings(2000000, MSBFIRST, SPI_MODE0); break;
  593. case 3: settings = SPISettings(1000000, MSBFIRST, SPI_MODE0); break;
  594. case 4: settings = SPISettings(500000, MSBFIRST, SPI_MODE0); break;
  595. case 5: settings = SPISettings(250000, MSBFIRST, SPI_MODE0); break;
  596. default: settings = SPISettings(125000, MSBFIRST, SPI_MODE0);
  597. }
  598. #endif
  599. return true;
  600. #endif
  601. }
  602. //------------------------------------------------------------------------------
  603. // wait for card to go not busy
  604. uint8_t Sd2Card::waitNotBusy(uint16_t timeoutMillis) {
  605. uint16_t t0 = millis();
  606. do {
  607. if (spiRec() == 0XFF) return true;
  608. }
  609. while (((uint16_t)millis() - t0) < timeoutMillis);
  610. return false;
  611. }
  612. //------------------------------------------------------------------------------
  613. /** Wait for start block token */
  614. uint8_t Sd2Card::waitStartBlock(void) {
  615. uint16_t t0 = millis();
  616. while ((status_ = spiRec()) == 0XFF) {
  617. if (((uint16_t)millis() - t0) > SD_READ_TIMEOUT) {
  618. error(SD_CARD_ERROR_READ_TIMEOUT);
  619. goto fail;
  620. }
  621. }
  622. if (status_ != DATA_START_BLOCK) {
  623. error(SD_CARD_ERROR_READ);
  624. goto fail;
  625. }
  626. return true;
  627. fail:
  628. chipSelectHigh();
  629. return false;
  630. }
  631. //------------------------------------------------------------------------------
  632. /**
  633. * Writes a 512 byte block to an SD card.
  634. *
  635. * \param[in] blockNumber Logical block to be written.
  636. * \param[in] src Pointer to the location of the data to be written.
  637. * \return The value one, true, is returned for success and
  638. * the value zero, false, is returned for failure.
  639. */
  640. uint8_t Sd2Card::writeBlock(uint32_t blockNumber, const uint8_t* src) {
  641. #if SD_PROTECT_BLOCK_ZERO
  642. // don't allow write to first block
  643. if (blockNumber == 0) {
  644. error(SD_CARD_ERROR_WRITE_BLOCK_ZERO);
  645. goto fail;
  646. }
  647. #endif // SD_PROTECT_BLOCK_ZERO
  648. // use address if not SDHC card
  649. if (type() != SD_CARD_TYPE_SDHC) blockNumber <<= 9;
  650. if (cardCommand(CMD24, blockNumber)) {
  651. error(SD_CARD_ERROR_CMD24);
  652. goto fail;
  653. }
  654. if (!writeData(DATA_START_BLOCK, src)) goto fail;
  655. // wait for flash programming to complete
  656. if (!waitNotBusy(SD_WRITE_TIMEOUT)) {
  657. error(SD_CARD_ERROR_WRITE_TIMEOUT);
  658. goto fail;
  659. }
  660. // response is r2 so get and check two bytes for nonzero
  661. if (cardCommand(CMD13, 0) || spiRec()) {
  662. error(SD_CARD_ERROR_WRITE_PROGRAMMING);
  663. goto fail;
  664. }
  665. chipSelectHigh();
  666. return true;
  667. fail:
  668. chipSelectHigh();
  669. return false;
  670. }
  671. //------------------------------------------------------------------------------
  672. /** Write one data block in a multiple block write sequence */
  673. uint8_t Sd2Card::writeData(const uint8_t* src) {
  674. // wait for previous write to finish
  675. if (!waitNotBusy(SD_WRITE_TIMEOUT)) {
  676. error(SD_CARD_ERROR_WRITE_MULTIPLE);
  677. chipSelectHigh();
  678. return false;
  679. }
  680. return writeData(WRITE_MULTIPLE_TOKEN, src);
  681. }
  682. //------------------------------------------------------------------------------
  683. // send one block of data for write block or write multiple blocks
  684. uint8_t Sd2Card::writeData(uint8_t token, const uint8_t* src) {
  685. #ifdef OPTIMIZE_HARDWARE_SPI
  686. // send data - optimized loop
  687. SPDR = token;
  688. // send two byte per iteration
  689. for (uint16_t i = 0; i < 512; i += 2) {
  690. while (!(SPSR & (1 << SPIF)));
  691. SPDR = src[i];
  692. while (!(SPSR & (1 << SPIF)));
  693. SPDR = src[i+1];
  694. }
  695. // wait for last data byte
  696. while (!(SPSR & (1 << SPIF)));
  697. #else // OPTIMIZE_HARDWARE_SPI
  698. spiSend(token);
  699. for (uint16_t i = 0; i < 512; i++) {
  700. spiSend(src[i]);
  701. }
  702. #endif // OPTIMIZE_HARDWARE_SPI
  703. spiSend(0xff); // dummy crc
  704. spiSend(0xff); // dummy crc
  705. status_ = spiRec();
  706. if ((status_ & DATA_RES_MASK) != DATA_RES_ACCEPTED) {
  707. error(SD_CARD_ERROR_WRITE);
  708. chipSelectHigh();
  709. return false;
  710. }
  711. return true;
  712. }
  713. //------------------------------------------------------------------------------
  714. /** Start a write multiple blocks sequence.
  715. *
  716. * \param[in] blockNumber Address of first block in sequence.
  717. * \param[in] eraseCount The number of blocks to be pre-erased.
  718. *
  719. * \note This function is used with writeData() and writeStop()
  720. * for optimized multiple block writes.
  721. *
  722. * \return The value one, true, is returned for success and
  723. * the value zero, false, is returned for failure.
  724. */
  725. uint8_t Sd2Card::writeStart(uint32_t blockNumber, uint32_t eraseCount) {
  726. #if SD_PROTECT_BLOCK_ZERO
  727. // don't allow write to first block
  728. if (blockNumber == 0) {
  729. error(SD_CARD_ERROR_WRITE_BLOCK_ZERO);
  730. goto fail;
  731. }
  732. #endif // SD_PROTECT_BLOCK_ZERO
  733. // send pre-erase count
  734. if (cardAcmd(ACMD23, eraseCount)) {
  735. error(SD_CARD_ERROR_ACMD23);
  736. goto fail;
  737. }
  738. // use address if not SDHC card
  739. if (type() != SD_CARD_TYPE_SDHC) blockNumber <<= 9;
  740. if (cardCommand(CMD25, blockNumber)) {
  741. error(SD_CARD_ERROR_CMD25);
  742. goto fail;
  743. }
  744. return true;
  745. fail:
  746. chipSelectHigh();
  747. return false;
  748. }
  749. //------------------------------------------------------------------------------
  750. /** End a write multiple blocks sequence.
  751. *
  752. * \return The value one, true, is returned for success and
  753. * the value zero, false, is returned for failure.
  754. */
  755. uint8_t Sd2Card::writeStop(void) {
  756. if (!waitNotBusy(SD_WRITE_TIMEOUT)) goto fail;
  757. spiSend(STOP_TRAN_TOKEN);
  758. if (!waitNotBusy(SD_WRITE_TIMEOUT)) goto fail;
  759. chipSelectHigh();
  760. return true;
  761. fail:
  762. error(SD_CARD_ERROR_STOP_TRAN);
  763. chipSelectHigh();
  764. return false;
  765. }