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.

Sd2Card.cpp 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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__) || defined(__MK64FX512__) || defined(__MK66FX1M0__)
  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. //------------------------------------------------------------------------------
  138. #else
  139. // functions for hardware SPI
  140. /** Send a byte to the card */
  141. static void spiSend(uint8_t b) {
  142. SPDR = b;
  143. while (!(SPSR & (1 << SPIF)));
  144. }
  145. /** Receive a byte from the card */
  146. static uint8_t spiRec(void) {
  147. spiSend(0XFF);
  148. return SPDR;
  149. }
  150. #endif
  151. //------------------------------------------------------------------------------
  152. // send command and return error code. Return zero for OK
  153. uint8_t Sd2Card::cardCommand(uint8_t cmd, uint32_t arg) {
  154. // end read if in partialBlockRead mode
  155. readEnd();
  156. // select card
  157. chipSelectLow();
  158. // wait up to 300 ms if busy
  159. waitNotBusy(300);
  160. // send command
  161. spiSend(cmd | 0x40);
  162. // send argument
  163. for (int8_t s = 24; s >= 0; s -= 8) spiSend(arg >> s);
  164. // send CRC
  165. uint8_t crc = 0XFF;
  166. if (cmd == CMD0) crc = 0X95; // correct crc for CMD0 with arg 0
  167. if (cmd == CMD8) crc = 0X87; // correct crc for CMD8 with arg 0X1AA
  168. spiSend(crc);
  169. // wait for response
  170. for (uint8_t i = 0; ((status_ = spiRec()) & 0X80) && i != 0XFF; i++);
  171. return status_;
  172. }
  173. //------------------------------------------------------------------------------
  174. #ifdef SPI_HAS_TRANSACTION
  175. static uint8_t chip_select_asserted = 0;
  176. #endif
  177. void Sd2Card::chipSelectHigh(void) {
  178. digitalWrite(chipSelectPin_, HIGH);
  179. #ifdef SPI_HAS_TRANSACTION
  180. if (chip_select_asserted) {
  181. chip_select_asserted = 0;
  182. SPI.endTransaction();
  183. }
  184. #endif
  185. }
  186. //------------------------------------------------------------------------------
  187. void Sd2Card::chipSelectLow(void) {
  188. #ifdef SPI_HAS_TRANSACTION
  189. if (!chip_select_asserted) {
  190. chip_select_asserted = 1;
  191. SPI.beginTransaction(settings);
  192. }
  193. #endif
  194. digitalWrite(chipSelectPin_, LOW);
  195. }
  196. //------------------------------------------------------------------------------
  197. /**
  198. * Initialize an SD flash memory card.
  199. *
  200. * \param[in] sckRateID SPI clock rate selector. See setSckRate().
  201. * \param[in] chipSelectPin SD chip select pin number.
  202. *
  203. * \return The value one, true, is returned for success and
  204. * the value zero, false, is returned for failure. The reason for failure
  205. * can be determined by calling errorCode() and errorData().
  206. */
  207. uint8_t Sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin) {
  208. errorCode_ = inBlock_ = type_ = 0;
  209. chipSelectPin_ = chipSelectPin;
  210. // 16-bit init start time allows over a minute
  211. uint16_t t0 = (uint16_t)millis();
  212. uint32_t arg;
  213. digitalWrite(chipSelectPin_, HIGH);
  214. pinMode(chipSelectPin_, OUTPUT);
  215. digitalWrite(chipSelectPin_, HIGH);
  216. #ifdef USE_TEENSY3_SPI
  217. spiBegin();
  218. spiInit(6);
  219. #else
  220. // set pin modes
  221. pinMode(SPI_MISO_PIN, INPUT);
  222. pinMode(SPI_MOSI_PIN, OUTPUT);
  223. pinMode(SPI_SCK_PIN, OUTPUT);
  224. // SS must be in output mode even it is not chip select
  225. pinMode(SS_PIN, OUTPUT);
  226. digitalWrite(SS_PIN, HIGH); // disable any SPI device using hardware SS pin
  227. // Enable SPI, Master, clock rate f_osc/128
  228. SPCR = (1 << SPE) | (1 << MSTR) | (1 << SPR1) | (1 << SPR0);
  229. // clear double speed
  230. SPSR &= ~(1 << SPI2X);
  231. #ifdef SPI_HAS_TRANSACTION
  232. settings = SPISettings(250000, MSBFIRST, SPI_MODE0);
  233. #endif
  234. #endif // not USE_TEENSY3_SPI
  235. // must supply min of 74 clock cycles with CS high.
  236. #ifdef SPI_HAS_TRANSACTION
  237. SPI.beginTransaction(settings);
  238. #endif
  239. for (uint8_t i = 0; i < 10; i++) spiSend(0XFF);
  240. #ifdef SPI_HAS_TRANSACTION
  241. SPI.endTransaction();
  242. #endif
  243. chipSelectLow();
  244. // command to go idle in SPI mode
  245. while ((status_ = cardCommand(CMD0, 0)) != R1_IDLE_STATE) {
  246. if (((uint16_t)(millis() - t0)) > SD_INIT_TIMEOUT) {
  247. error(SD_CARD_ERROR_CMD0);
  248. goto fail;
  249. }
  250. }
  251. // check SD version
  252. if ((cardCommand(CMD8, 0x1AA) & R1_ILLEGAL_COMMAND)) {
  253. type(SD_CARD_TYPE_SD1);
  254. } else {
  255. // only need last byte of r7 response
  256. for (uint8_t i = 0; i < 4; i++) status_ = spiRec();
  257. if (status_ != 0XAA) {
  258. error(SD_CARD_ERROR_CMD8);
  259. goto fail;
  260. }
  261. type(SD_CARD_TYPE_SD2);
  262. }
  263. // initialize card and send host supports SDHC if SD2
  264. arg = type() == SD_CARD_TYPE_SD2 ? 0X40000000 : 0;
  265. while ((status_ = cardAcmd(ACMD41, arg)) != R1_READY_STATE) {
  266. // check for timeout
  267. if (((uint16_t)(millis() - t0)) > SD_INIT_TIMEOUT) {
  268. error(SD_CARD_ERROR_ACMD41);
  269. goto fail;
  270. }
  271. }
  272. // if SD2 read OCR register to check for SDHC card
  273. if (type() == SD_CARD_TYPE_SD2) {
  274. if (cardCommand(CMD58, 0)) {
  275. error(SD_CARD_ERROR_CMD58);
  276. goto fail;
  277. }
  278. if ((spiRec() & 0XC0) == 0XC0) type(SD_CARD_TYPE_SDHC);
  279. // discard rest of ocr - contains allowed voltage range
  280. for (uint8_t i = 0; i < 3; i++) spiRec();
  281. }
  282. chipSelectHigh();
  283. return setSckRate(sckRateID);
  284. fail:
  285. chipSelectHigh();
  286. return false;
  287. }
  288. //------------------------------------------------------------------------------
  289. /**
  290. * Read a 512 byte block from an SD card device.
  291. *
  292. * \param[in] block Logical block to be read.
  293. * \param[out] dst Pointer to the location that will receive the data.
  294. * \return The value one, true, is returned for success and
  295. * the value zero, false, is returned for failure.
  296. */
  297. uint8_t Sd2Card::readBlock(uint32_t block, uint8_t* dst) {
  298. return readData(block, 0, 512, dst);
  299. }
  300. //------------------------------------------------------------------------------
  301. /**
  302. * Read part of a 512 byte block from an SD card.
  303. *
  304. * \param[in] block Logical block to be read.
  305. * \param[in] offset Number of bytes to skip at start of block
  306. * \param[out] dst Pointer to the location that will receive the data.
  307. * \param[in] count Number of bytes to read
  308. * \return The value one, true, is returned for success and
  309. * the value zero, false, is returned for failure.
  310. */
  311. uint8_t Sd2Card::readData(uint32_t block,
  312. uint16_t offset, uint16_t count, uint8_t* dst) {
  313. #if !defined(USE_TEENSY3_SPI) && defined(OPTIMIZE_HARDWARE_SPI)
  314. uint16_t n;
  315. #endif
  316. if (count == 0) return true;
  317. if ((count + offset) > 512) {
  318. goto fail;
  319. }
  320. if (!inBlock_ || block != block_ || offset < offset_) {
  321. block_ = block;
  322. // use address if not SDHC card
  323. if (type()!= SD_CARD_TYPE_SDHC) block <<= 9;
  324. if (cardCommand(CMD17, block)) {
  325. error(SD_CARD_ERROR_CMD17);
  326. goto fail;
  327. }
  328. if (!waitStartBlock()) {
  329. goto fail;
  330. }
  331. offset_ = 0;
  332. inBlock_ = 1;
  333. }
  334. #if defined(USE_TEENSY3_SPI)
  335. // skip data before offset
  336. //for (;offset_ < offset; offset_++) {
  337. //spiRec();
  338. //}
  339. spiRecIgnore(offset);
  340. spiRec(dst, count);
  341. #elif defined(OPTIMIZE_HARDWARE_SPI)
  342. // start first spi transfer
  343. SPDR = 0XFF;
  344. // skip data before offset
  345. for (;offset_ < offset; offset_++) {
  346. while (!(SPSR & (1 << SPIF)));
  347. SPDR = 0XFF;
  348. }
  349. // transfer data
  350. n = count - 1;
  351. for (uint16_t i = 0; i < n; i++) {
  352. while (!(SPSR & (1 << SPIF)));
  353. dst[i] = SPDR;
  354. SPDR = 0XFF;
  355. }
  356. // wait for last byte
  357. while (!(SPSR & (1 << SPIF)));
  358. dst[n] = SPDR;
  359. #else // OPTIMIZE_HARDWARE_SPI
  360. // skip data before offset
  361. for (;offset_ < offset; offset_++) {
  362. spiRec();
  363. }
  364. // transfer data
  365. for (uint16_t i = 0; i < count; i++) {
  366. dst[i] = spiRec();
  367. }
  368. #endif // OPTIMIZE_HARDWARE_SPI
  369. offset_ += count;
  370. if (offset_ >= 512) {
  371. // read rest of data, checksum and set chip select high
  372. readEnd();
  373. }
  374. return true;
  375. fail:
  376. chipSelectHigh();
  377. return false;
  378. }
  379. //------------------------------------------------------------------------------
  380. /** Skip remaining data in a block when in partial block read mode. */
  381. void Sd2Card::readEnd(void) {
  382. if (inBlock_) {
  383. // skip data and crc
  384. #if defined(USE_TEENSY3_SPI)
  385. if (offset_ < 514) {
  386. spiRecIgnore(514 - offset_);
  387. offset_ = 514;
  388. }
  389. #elif defined(OPTIMIZE_HARDWARE_SPI)
  390. // optimize skip for hardware
  391. SPDR = 0XFF;
  392. while (offset_++ < 513) {
  393. while (!(SPSR & (1 << SPIF)));
  394. SPDR = 0XFF;
  395. }
  396. // wait for last crc byte
  397. while (!(SPSR & (1 << SPIF)));
  398. #else // OPTIMIZE_HARDWARE_SPI
  399. while (offset_++ < 514) spiRec();
  400. #endif // OPTIMIZE_HARDWARE_SPI
  401. chipSelectHigh();
  402. inBlock_ = 0;
  403. }
  404. }
  405. //------------------------------------------------------------------------------
  406. /** read CID or CSR register */
  407. uint8_t Sd2Card::readRegister(uint8_t cmd, void* buf) {
  408. uint8_t* dst = reinterpret_cast<uint8_t*>(buf);
  409. if (cardCommand(cmd, 0)) {
  410. error(SD_CARD_ERROR_READ_REG);
  411. goto fail;
  412. }
  413. if (!waitStartBlock()) goto fail;
  414. // transfer data
  415. for (uint16_t i = 0; i < 16; i++) dst[i] = spiRec();
  416. spiRec(); // get first crc byte
  417. spiRec(); // get second crc byte
  418. chipSelectHigh();
  419. return true;
  420. fail:
  421. chipSelectHigh();
  422. return false;
  423. }
  424. //------------------------------------------------------------------------------
  425. /**
  426. * Set the SPI clock rate.
  427. *
  428. * \param[in] sckRateID A value in the range [0, 6].
  429. *
  430. * 0 = 8 MHz
  431. * 1 = 4 MHz
  432. * 2 = 2 MHz
  433. * 3 = 1 MHz
  434. * 4 = 500 kHz
  435. * 5 = 125 kHz
  436. * 6 = 63 kHz
  437. *
  438. * The SPI clock will be set to F_CPU/pow(2, 1 + sckRateID). The maximum
  439. * SPI rate is F_CPU/2 for \a sckRateID = 0 and the minimum rate is F_CPU/128
  440. * for \a scsRateID = 6.
  441. *
  442. * \return The value one, true, is returned for success and the value zero,
  443. * false, is returned for an invalid value of \a sckRateID.
  444. */
  445. uint8_t Sd2Card::setSckRate(uint8_t sckRateID) {
  446. #ifdef USE_TEENSY3_SPI
  447. spiInit(sckRateID);
  448. return true;
  449. #else
  450. if (sckRateID > 6) sckRateID = 6;
  451. // see avr processor datasheet for SPI register bit definitions
  452. if ((sckRateID & 1) || sckRateID == 6) {
  453. SPSR &= ~(1 << SPI2X);
  454. } else {
  455. SPSR |= (1 << SPI2X);
  456. }
  457. SPCR &= ~((1 <<SPR1) | (1 << SPR0));
  458. SPCR |= (sckRateID & 4 ? (1 << SPR1) : 0)
  459. | (sckRateID & 2 ? (1 << SPR0) : 0);
  460. #ifdef SPI_HAS_TRANSACTION
  461. switch (sckRateID) {
  462. case 0: settings = SPISettings(8000000, MSBFIRST, SPI_MODE0); break;
  463. case 1: settings = SPISettings(4000000, MSBFIRST, SPI_MODE0); break;
  464. case 2: settings = SPISettings(2000000, MSBFIRST, SPI_MODE0); break;
  465. case 3: settings = SPISettings(1000000, MSBFIRST, SPI_MODE0); break;
  466. case 4: settings = SPISettings(500000, MSBFIRST, SPI_MODE0); break;
  467. case 5: settings = SPISettings(250000, MSBFIRST, SPI_MODE0); break;
  468. default: settings = SPISettings(125000, MSBFIRST, SPI_MODE0);
  469. }
  470. #endif
  471. return true;
  472. #endif
  473. }
  474. //------------------------------------------------------------------------------
  475. // wait for card to go not busy
  476. uint8_t Sd2Card::waitNotBusy(uint16_t timeoutMillis) {
  477. uint16_t t0 = millis();
  478. do {
  479. if (spiRec() == 0XFF) return true;
  480. }
  481. while (((uint16_t)millis() - t0) < timeoutMillis);
  482. return false;
  483. }
  484. //------------------------------------------------------------------------------
  485. /** Wait for start block token */
  486. uint8_t Sd2Card::waitStartBlock(void) {
  487. uint16_t t0 = millis();
  488. while ((status_ = spiRec()) == 0XFF) {
  489. if (((uint16_t)millis() - t0) > SD_READ_TIMEOUT) {
  490. error(SD_CARD_ERROR_READ_TIMEOUT);
  491. goto fail;
  492. }
  493. }
  494. if (status_ != DATA_START_BLOCK) {
  495. error(SD_CARD_ERROR_READ);
  496. goto fail;
  497. }
  498. return true;
  499. fail:
  500. chipSelectHigh();
  501. return false;
  502. }
  503. //------------------------------------------------------------------------------
  504. /**
  505. * Writes a 512 byte block to an SD card.
  506. *
  507. * \param[in] blockNumber Logical block to be written.
  508. * \param[in] src Pointer to the location of the data to be written.
  509. * \return The value one, true, is returned for success and
  510. * the value zero, false, is returned for failure.
  511. */
  512. uint8_t Sd2Card::writeBlock(uint32_t blockNumber, const uint8_t* src) {
  513. #if SD_PROTECT_BLOCK_ZERO
  514. // don't allow write to first block
  515. if (blockNumber == 0) {
  516. error(SD_CARD_ERROR_WRITE_BLOCK_ZERO);
  517. goto fail;
  518. }
  519. #endif // SD_PROTECT_BLOCK_ZERO
  520. // use address if not SDHC card
  521. if (type() != SD_CARD_TYPE_SDHC) blockNumber <<= 9;
  522. if (cardCommand(CMD24, blockNumber)) {
  523. error(SD_CARD_ERROR_CMD24);
  524. goto fail;
  525. }
  526. if (!writeData(DATA_START_BLOCK, src)) goto fail;
  527. // wait for flash programming to complete
  528. if (!waitNotBusy(SD_WRITE_TIMEOUT)) {
  529. error(SD_CARD_ERROR_WRITE_TIMEOUT);
  530. goto fail;
  531. }
  532. // response is r2 so get and check two bytes for nonzero
  533. if (cardCommand(CMD13, 0) || spiRec()) {
  534. error(SD_CARD_ERROR_WRITE_PROGRAMMING);
  535. goto fail;
  536. }
  537. chipSelectHigh();
  538. return true;
  539. fail:
  540. chipSelectHigh();
  541. return false;
  542. }
  543. //------------------------------------------------------------------------------
  544. // send one block of data for write block or write multiple blocks
  545. uint8_t Sd2Card::writeData(uint8_t token, const uint8_t* src) {
  546. #ifdef OPTIMIZE_HARDWARE_SPI
  547. // send data - optimized loop
  548. SPDR = token;
  549. // send two byte per iteration
  550. for (uint16_t i = 0; i < 512; i += 2) {
  551. while (!(SPSR & (1 << SPIF)));
  552. SPDR = src[i];
  553. while (!(SPSR & (1 << SPIF)));
  554. SPDR = src[i+1];
  555. }
  556. // wait for last data byte
  557. while (!(SPSR & (1 << SPIF)));
  558. #else // OPTIMIZE_HARDWARE_SPI
  559. spiSend(token);
  560. for (uint16_t i = 0; i < 512; i++) {
  561. spiSend(src[i]);
  562. }
  563. #endif // OPTIMIZE_HARDWARE_SPI
  564. spiSend(0xff); // dummy crc
  565. spiSend(0xff); // dummy crc
  566. status_ = spiRec();
  567. if ((status_ & DATA_RES_MASK) != DATA_RES_ACCEPTED) {
  568. error(SD_CARD_ERROR_WRITE);
  569. chipSelectHigh();
  570. return false;
  571. }
  572. return true;
  573. }