You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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