Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

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