Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

Sd2Card.cpp 16KB

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