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

884 lines
25KB

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