Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

10 лет назад
10 лет назад
10 лет назад
10 лет назад
10 лет назад
10 лет назад
10 лет назад
10 лет назад
10 лет назад
10 лет назад
10 лет назад
10 лет назад
10 лет назад
10 лет назад
10 лет назад
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  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. //uint16_t n;
  442. if (count == 0) return true;
  443. if ((count + offset) > 512) {
  444. goto fail;
  445. }
  446. if (!inBlock_ || block != block_ || offset < offset_) {
  447. block_ = block;
  448. // use address if not SDHC card
  449. if (type()!= SD_CARD_TYPE_SDHC) block <<= 9;
  450. if (cardCommand(CMD17, block)) {
  451. error(SD_CARD_ERROR_CMD17);
  452. goto fail;
  453. }
  454. if (!waitStartBlock()) {
  455. goto fail;
  456. }
  457. offset_ = 0;
  458. inBlock_ = 1;
  459. }
  460. #if defined(USE_TEENSY3_SPI)
  461. // skip data before offset
  462. //for (;offset_ < offset; offset_++) {
  463. //spiRec();
  464. //}
  465. spiRecIgnore(offset);
  466. spiRec(dst, count);
  467. #elif defined(OPTIMIZE_HARDWARE_SPI)
  468. // start first spi transfer
  469. SPDR = 0XFF;
  470. // skip data before offset
  471. for (;offset_ < offset; offset_++) {
  472. while (!(SPSR & (1 << SPIF)));
  473. SPDR = 0XFF;
  474. }
  475. // transfer data
  476. n = count - 1;
  477. for (uint16_t i = 0; i < n; i++) {
  478. while (!(SPSR & (1 << SPIF)));
  479. dst[i] = SPDR;
  480. SPDR = 0XFF;
  481. }
  482. // wait for last byte
  483. while (!(SPSR & (1 << SPIF)));
  484. dst[n] = SPDR;
  485. #else // OPTIMIZE_HARDWARE_SPI
  486. // skip data before offset
  487. for (;offset_ < offset; offset_++) {
  488. spiRec();
  489. }
  490. // transfer data
  491. for (uint16_t i = 0; i < count; i++) {
  492. dst[i] = spiRec();
  493. }
  494. #endif // OPTIMIZE_HARDWARE_SPI
  495. offset_ += count;
  496. if (!partialBlockRead_ || offset_ >= 512) {
  497. // read rest of data, checksum and set chip select high
  498. readEnd();
  499. }
  500. return true;
  501. fail:
  502. chipSelectHigh();
  503. return false;
  504. }
  505. //------------------------------------------------------------------------------
  506. /** Skip remaining data in a block when in partial block read mode. */
  507. void Sd2Card::readEnd(void) {
  508. if (inBlock_) {
  509. // skip data and crc
  510. #if defined(USE_TEENSY3_SPI)
  511. if (offset_ < 514) {
  512. spiRecIgnore(514 - offset_);
  513. offset_ = 514;
  514. }
  515. #elif defined(OPTIMIZE_HARDWARE_SPI)
  516. // optimize skip for hardware
  517. SPDR = 0XFF;
  518. while (offset_++ < 513) {
  519. while (!(SPSR & (1 << SPIF)));
  520. SPDR = 0XFF;
  521. }
  522. // wait for last crc byte
  523. while (!(SPSR & (1 << SPIF)));
  524. #else // OPTIMIZE_HARDWARE_SPI
  525. while (offset_++ < 514) spiRec();
  526. #endif // OPTIMIZE_HARDWARE_SPI
  527. chipSelectHigh();
  528. inBlock_ = 0;
  529. }
  530. }
  531. //------------------------------------------------------------------------------
  532. /** read CID or CSR register */
  533. uint8_t Sd2Card::readRegister(uint8_t cmd, void* buf) {
  534. uint8_t* dst = reinterpret_cast<uint8_t*>(buf);
  535. if (cardCommand(cmd, 0)) {
  536. error(SD_CARD_ERROR_READ_REG);
  537. goto fail;
  538. }
  539. if (!waitStartBlock()) goto fail;
  540. // transfer data
  541. for (uint16_t i = 0; i < 16; i++) dst[i] = spiRec();
  542. spiRec(); // get first crc byte
  543. spiRec(); // get second crc byte
  544. chipSelectHigh();
  545. return true;
  546. fail:
  547. chipSelectHigh();
  548. return false;
  549. }
  550. //------------------------------------------------------------------------------
  551. /**
  552. * Set the SPI clock rate.
  553. *
  554. * \param[in] sckRateID A value in the range [0, 6].
  555. *
  556. * 0 = 8 MHz
  557. * 1 = 4 MHz
  558. * 2 = 2 MHz
  559. * 3 = 1 MHz
  560. * 4 = 500 kHz
  561. * 5 = 125 kHz
  562. * 6 = 63 kHz
  563. *
  564. * The SPI clock will be set to F_CPU/pow(2, 1 + sckRateID). The maximum
  565. * SPI rate is F_CPU/2 for \a sckRateID = 0 and the minimum rate is F_CPU/128
  566. * for \a scsRateID = 6.
  567. *
  568. * \return The value one, true, is returned for success and the value zero,
  569. * false, is returned for an invalid value of \a sckRateID.
  570. */
  571. uint8_t Sd2Card::setSckRate(uint8_t sckRateID) {
  572. #ifdef USE_TEENSY3_SPI
  573. spiInit(sckRateID);
  574. return true;
  575. #else
  576. if (sckRateID > 6) sckRateID = 6;
  577. // see avr processor datasheet for SPI register bit definitions
  578. if ((sckRateID & 1) || sckRateID == 6) {
  579. SPSR &= ~(1 << SPI2X);
  580. } else {
  581. SPSR |= (1 << SPI2X);
  582. }
  583. SPCR &= ~((1 <<SPR1) | (1 << SPR0));
  584. SPCR |= (sckRateID & 4 ? (1 << SPR1) : 0)
  585. | (sckRateID & 2 ? (1 << SPR0) : 0);
  586. #ifdef SPI_HAS_TRANSACTION
  587. switch (sckRateID) {
  588. case 0: settings = SPISettings(8000000, MSBFIRST, SPI_MODE0); break;
  589. case 1: settings = SPISettings(4000000, MSBFIRST, SPI_MODE0); break;
  590. case 2: settings = SPISettings(2000000, MSBFIRST, SPI_MODE0); break;
  591. case 3: settings = SPISettings(1000000, MSBFIRST, SPI_MODE0); break;
  592. case 4: settings = SPISettings(500000, MSBFIRST, SPI_MODE0); break;
  593. case 5: settings = SPISettings(250000, MSBFIRST, SPI_MODE0); break;
  594. default: settings = SPISettings(125000, MSBFIRST, SPI_MODE0);
  595. }
  596. #endif
  597. return true;
  598. #endif
  599. }
  600. //------------------------------------------------------------------------------
  601. // wait for card to go not busy
  602. uint8_t Sd2Card::waitNotBusy(uint16_t timeoutMillis) {
  603. uint16_t t0 = millis();
  604. do {
  605. if (spiRec() == 0XFF) return true;
  606. }
  607. while (((uint16_t)millis() - t0) < timeoutMillis);
  608. return false;
  609. }
  610. //------------------------------------------------------------------------------
  611. /** Wait for start block token */
  612. uint8_t Sd2Card::waitStartBlock(void) {
  613. uint16_t t0 = millis();
  614. while ((status_ = spiRec()) == 0XFF) {
  615. if (((uint16_t)millis() - t0) > SD_READ_TIMEOUT) {
  616. error(SD_CARD_ERROR_READ_TIMEOUT);
  617. goto fail;
  618. }
  619. }
  620. if (status_ != DATA_START_BLOCK) {
  621. error(SD_CARD_ERROR_READ);
  622. goto fail;
  623. }
  624. return true;
  625. fail:
  626. chipSelectHigh();
  627. return false;
  628. }
  629. //------------------------------------------------------------------------------
  630. /**
  631. * Writes a 512 byte block to an SD card.
  632. *
  633. * \param[in] blockNumber Logical block to be written.
  634. * \param[in] src Pointer to the location of the data to be written.
  635. * \return The value one, true, is returned for success and
  636. * the value zero, false, is returned for failure.
  637. */
  638. uint8_t Sd2Card::writeBlock(uint32_t blockNumber, const uint8_t* src) {
  639. #if SD_PROTECT_BLOCK_ZERO
  640. // don't allow write to first block
  641. if (blockNumber == 0) {
  642. error(SD_CARD_ERROR_WRITE_BLOCK_ZERO);
  643. goto fail;
  644. }
  645. #endif // SD_PROTECT_BLOCK_ZERO
  646. // use address if not SDHC card
  647. if (type() != SD_CARD_TYPE_SDHC) blockNumber <<= 9;
  648. if (cardCommand(CMD24, blockNumber)) {
  649. error(SD_CARD_ERROR_CMD24);
  650. goto fail;
  651. }
  652. if (!writeData(DATA_START_BLOCK, src)) goto fail;
  653. // wait for flash programming to complete
  654. if (!waitNotBusy(SD_WRITE_TIMEOUT)) {
  655. error(SD_CARD_ERROR_WRITE_TIMEOUT);
  656. goto fail;
  657. }
  658. // response is r2 so get and check two bytes for nonzero
  659. if (cardCommand(CMD13, 0) || spiRec()) {
  660. error(SD_CARD_ERROR_WRITE_PROGRAMMING);
  661. goto fail;
  662. }
  663. chipSelectHigh();
  664. return true;
  665. fail:
  666. chipSelectHigh();
  667. return false;
  668. }
  669. //------------------------------------------------------------------------------
  670. /** Write one data block in a multiple block write sequence */
  671. uint8_t Sd2Card::writeData(const uint8_t* src) {
  672. // wait for previous write to finish
  673. if (!waitNotBusy(SD_WRITE_TIMEOUT)) {
  674. error(SD_CARD_ERROR_WRITE_MULTIPLE);
  675. chipSelectHigh();
  676. return false;
  677. }
  678. return writeData(WRITE_MULTIPLE_TOKEN, src);
  679. }
  680. //------------------------------------------------------------------------------
  681. // send one block of data for write block or write multiple blocks
  682. uint8_t Sd2Card::writeData(uint8_t token, const uint8_t* src) {
  683. #ifdef OPTIMIZE_HARDWARE_SPI
  684. // send data - optimized loop
  685. SPDR = token;
  686. // send two byte per iteration
  687. for (uint16_t i = 0; i < 512; i += 2) {
  688. while (!(SPSR & (1 << SPIF)));
  689. SPDR = src[i];
  690. while (!(SPSR & (1 << SPIF)));
  691. SPDR = src[i+1];
  692. }
  693. // wait for last data byte
  694. while (!(SPSR & (1 << SPIF)));
  695. #else // OPTIMIZE_HARDWARE_SPI
  696. spiSend(token);
  697. for (uint16_t i = 0; i < 512; i++) {
  698. spiSend(src[i]);
  699. }
  700. #endif // OPTIMIZE_HARDWARE_SPI
  701. spiSend(0xff); // dummy crc
  702. spiSend(0xff); // dummy crc
  703. status_ = spiRec();
  704. if ((status_ & DATA_RES_MASK) != DATA_RES_ACCEPTED) {
  705. error(SD_CARD_ERROR_WRITE);
  706. chipSelectHigh();
  707. return false;
  708. }
  709. return true;
  710. }
  711. //------------------------------------------------------------------------------
  712. /** Start a write multiple blocks sequence.
  713. *
  714. * \param[in] blockNumber Address of first block in sequence.
  715. * \param[in] eraseCount The number of blocks to be pre-erased.
  716. *
  717. * \note This function is used with writeData() and writeStop()
  718. * for optimized multiple block writes.
  719. *
  720. * \return The value one, true, is returned for success and
  721. * the value zero, false, is returned for failure.
  722. */
  723. uint8_t Sd2Card::writeStart(uint32_t blockNumber, uint32_t eraseCount) {
  724. #if SD_PROTECT_BLOCK_ZERO
  725. // don't allow write to first block
  726. if (blockNumber == 0) {
  727. error(SD_CARD_ERROR_WRITE_BLOCK_ZERO);
  728. goto fail;
  729. }
  730. #endif // SD_PROTECT_BLOCK_ZERO
  731. // send pre-erase count
  732. if (cardAcmd(ACMD23, eraseCount)) {
  733. error(SD_CARD_ERROR_ACMD23);
  734. goto fail;
  735. }
  736. // use address if not SDHC card
  737. if (type() != SD_CARD_TYPE_SDHC) blockNumber <<= 9;
  738. if (cardCommand(CMD25, blockNumber)) {
  739. error(SD_CARD_ERROR_CMD25);
  740. goto fail;
  741. }
  742. return true;
  743. fail:
  744. chipSelectHigh();
  745. return false;
  746. }
  747. //------------------------------------------------------------------------------
  748. /** End a write multiple blocks sequence.
  749. *
  750. * \return The value one, true, is returned for success and
  751. * the value zero, false, is returned for failure.
  752. */
  753. uint8_t Sd2Card::writeStop(void) {
  754. if (!waitNotBusy(SD_WRITE_TIMEOUT)) goto fail;
  755. spiSend(STOP_TRAN_TOKEN);
  756. if (!waitNotBusy(SD_WRITE_TIMEOUT)) goto fail;
  757. chipSelectHigh();
  758. return true;
  759. fail:
  760. error(SD_CARD_ERROR_STOP_TRAN);
  761. chipSelectHigh();
  762. return false;
  763. }