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.

540 lines
16KB

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