Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

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