Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

818 Zeilen
24KB

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