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

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