PlatformIO package of the Teensy core framework compatible with GCC 10 & C++20
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.

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