Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

507 lines
15KB

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