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.

пре 10 година
пре 10 година
пре 8 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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. uint16_t t0 = (uint16_t)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. if (((uint16_t)(millis() - t0)) > SD_INIT_TIMEOUT) {
  243. goto fail; // SD_CARD_ERROR_CMD0
  244. }
  245. }
  246. // check SD version
  247. if ((cardCommand(CMD8, 0x1AA) & R1_ILLEGAL_COMMAND)) {
  248. type_ = SD_CARD_TYPE_SD1;
  249. } else {
  250. // only need last byte of r7 response
  251. for (uint8_t i = 0; i < 4; i++) status_ = spiRec();
  252. if (status_ != 0XAA) {
  253. goto fail; // SD_CARD_ERROR_CMD8
  254. }
  255. type_ = SD_CARD_TYPE_SD2;
  256. }
  257. // initialize card and send host supports SDHC if SD2
  258. arg = (type_ == SD_CARD_TYPE_SD2) ? 0X40000000 : 0;
  259. while ((status_ = cardAcmd(ACMD41, arg)) != R1_READY_STATE) {
  260. // check for timeout
  261. if (((uint16_t)(millis() - t0)) > SD_INIT_TIMEOUT) {
  262. goto fail; // SD_CARD_ERROR_ACMD41
  263. }
  264. }
  265. // if SD2 read OCR register to check for SDHC card
  266. if (type_ == SD_CARD_TYPE_SD2) {
  267. if (cardCommand(CMD58, 0)) {
  268. goto fail; // SD_CARD_ERROR_CMD58
  269. }
  270. if ((spiRec() & 0XC0) == 0XC0) type_ = SD_CARD_TYPE_SDHC;
  271. // discard rest of ocr - contains allowed voltage range
  272. for (uint8_t i = 0; i < 3; i++) spiRec();
  273. }
  274. chipSelectHigh();
  275. return setSckRate(sckRateID);
  276. fail:
  277. chipSelectHigh();
  278. return false;
  279. }
  280. //------------------------------------------------------------------------------
  281. /**
  282. * Read a 512 byte block from an SD card device.
  283. *
  284. * \param[in] block Logical block to be read.
  285. * \param[out] dst Pointer to the location that will receive the data.
  286. * \return The value one, true, is returned for success and
  287. * the value zero, false, is returned for failure.
  288. */
  289. uint8_t Sd2Card::SD_readBlock(uint32_t block, uint8_t* dst)
  290. {
  291. // use address if not SDHC card
  292. if (type_ != SD_CARD_TYPE_SDHC) block <<= 9;
  293. chipSelectLow();
  294. if (cardCommand(CMD17, block)) {
  295. goto fail; // SD_CARD_ERROR_CMD17
  296. }
  297. if (!waitStartBlock()) {
  298. goto fail;
  299. }
  300. #ifdef USE_TEENSY3_SPI
  301. spiRec(dst, 512);
  302. spiRecIgnore(2);
  303. #else // OPTIMIZE_HARDWARE_SPI
  304. // start first spi transfer
  305. SPDR = 0XFF;
  306. // transfer data
  307. for (uint16_t i = 0; i < 511; i++) {
  308. while (!(SPSR & (1 << SPIF)));
  309. dst[i] = SPDR;
  310. SPDR = 0XFF;
  311. }
  312. // wait for last byte
  313. while (!(SPSR & (1 << SPIF)));
  314. dst[511] = SPDR;
  315. // skip CRC bytes
  316. spiRec();
  317. spiRec();
  318. #endif
  319. chipSelectHigh();
  320. return true;
  321. fail:
  322. chipSelectHigh();
  323. return false;
  324. }
  325. //------------------------------------------------------------------------------
  326. /**
  327. * Set the SPI clock rate.
  328. *
  329. * \param[in] sckRateID A value in the range [0, 6].
  330. *
  331. * 0 = 8 MHz
  332. * 1 = 4 MHz
  333. * 2 = 2 MHz
  334. * 3 = 1 MHz
  335. * 4 = 500 kHz
  336. * 5 = 125 kHz
  337. * 6 = 63 kHz
  338. *
  339. * The SPI clock will be set to F_CPU/pow(2, 1 + sckRateID). The maximum
  340. * SPI rate is F_CPU/2 for \a sckRateID = 0 and the minimum rate is F_CPU/128
  341. * for \a scsRateID = 6.
  342. *
  343. * \return The value one, true, is returned for success and the value zero,
  344. * false, is returned for an invalid value of \a sckRateID.
  345. */
  346. uint8_t Sd2Card::setSckRate(uint8_t sckRateID) {
  347. #ifdef USE_TEENSY3_SPI
  348. spiInit(sckRateID);
  349. return true;
  350. #else
  351. if (sckRateID > 6) sckRateID = 6;
  352. // see avr processor datasheet for SPI register bit definitions
  353. if ((sckRateID & 1) || sckRateID == 6) {
  354. SPSR &= ~(1 << SPI2X);
  355. } else {
  356. SPSR |= (1 << SPI2X);
  357. }
  358. SPCR &= ~((1 <<SPR1) | (1 << SPR0));
  359. SPCR |= (sckRateID & 4 ? (1 << SPR1) : 0)
  360. | (sckRateID & 2 ? (1 << SPR0) : 0);
  361. #ifdef SPI_HAS_TRANSACTION
  362. switch (sckRateID) {
  363. case 0: settings = SPISettings(8000000, MSBFIRST, SPI_MODE0); break;
  364. case 1: settings = SPISettings(4000000, MSBFIRST, SPI_MODE0); break;
  365. case 2: settings = SPISettings(2000000, MSBFIRST, SPI_MODE0); break;
  366. case 3: settings = SPISettings(1000000, MSBFIRST, SPI_MODE0); break;
  367. case 4: settings = SPISettings(500000, MSBFIRST, SPI_MODE0); break;
  368. case 5: settings = SPISettings(250000, MSBFIRST, SPI_MODE0); break;
  369. default: settings = SPISettings(125000, MSBFIRST, SPI_MODE0);
  370. }
  371. #endif
  372. return true;
  373. #endif
  374. }
  375. //------------------------------------------------------------------------------
  376. // wait for card to go not busy
  377. uint8_t Sd2Card::waitNotBusy(uint16_t timeoutMillis) {
  378. uint16_t t0 = millis();
  379. do {
  380. if (spiRec() == 0XFF) return true;
  381. }
  382. while (((uint16_t)millis() - t0) < timeoutMillis);
  383. return false;
  384. }
  385. //------------------------------------------------------------------------------
  386. /** Wait for start block token */
  387. uint8_t Sd2Card::waitStartBlock(void) {
  388. uint16_t t0 = millis();
  389. while ((status_ = spiRec()) == 0XFF) {
  390. if (((uint16_t)millis() - t0) > SD_READ_TIMEOUT) {
  391. return false; // SD_CARD_ERROR_READ_TIMEOUT
  392. }
  393. }
  394. if (status_ != DATA_START_BLOCK) {
  395. return false; // SD_CARD_ERROR_READ
  396. }
  397. return true;
  398. }
  399. //------------------------------------------------------------------------------
  400. /**
  401. * Writes a 512 byte block to an SD card.
  402. *
  403. * \param[in] blockNumber Logical block to be written.
  404. * \param[in] src Pointer to the location of the data to be written.
  405. * \return The value one, true, is returned for success and
  406. * the value zero, false, is returned for failure.
  407. */
  408. uint8_t Sd2Card::SD_writeBlock(uint32_t blockNumber, const uint8_t* src) {
  409. #if SD_PROTECT_BLOCK_ZERO
  410. // don't allow write to first block
  411. if (blockNumber == 0) {
  412. goto fail; // SD_CARD_ERROR_WRITE_BLOCK_ZERO
  413. }
  414. #endif // SD_PROTECT_BLOCK_ZERO
  415. // use address if not SDHC card
  416. if (type_ != SD_CARD_TYPE_SDHC) blockNumber <<= 9;
  417. chipSelectLow();
  418. if (cardCommand(CMD24, blockNumber)) {
  419. goto fail; // SD_CARD_ERROR_CMD24
  420. }
  421. if (!writeData(DATA_START_BLOCK, src)) goto fail;
  422. // wait for flash programming to complete
  423. if (!waitNotBusy(SD_WRITE_TIMEOUT)) {
  424. goto fail; // SD_CARD_ERROR_WRITE_TIMEOUT
  425. }
  426. // response is r2 so get and check two bytes for nonzero
  427. if (cardCommand(CMD13, 0) || spiRec()) {
  428. goto fail; // SD_CARD_ERROR_WRITE_PROGRAMMING
  429. }
  430. chipSelectHigh();
  431. return true;
  432. fail:
  433. chipSelectHigh();
  434. return false;
  435. }
  436. //------------------------------------------------------------------------------
  437. // send one block of data for write block or write multiple blocks
  438. uint8_t Sd2Card::writeData(uint8_t token, const uint8_t* src) {
  439. #ifdef OPTIMIZE_HARDWARE_SPI
  440. // send data - optimized loop
  441. SPDR = token;
  442. // send two byte per iteration
  443. for (uint16_t i = 0; i < 512; i += 2) {
  444. while (!(SPSR & (1 << SPIF)));
  445. SPDR = src[i];
  446. while (!(SPSR & (1 << SPIF)));
  447. SPDR = src[i+1];
  448. }
  449. // wait for last data byte
  450. while (!(SPSR & (1 << SPIF)));
  451. #else // OPTIMIZE_HARDWARE_SPI
  452. spiSend(token);
  453. for (uint16_t i = 0; i < 512; i++) {
  454. spiSend(src[i]);
  455. }
  456. #endif // OPTIMIZE_HARDWARE_SPI
  457. spiSend(0xff); // dummy crc
  458. spiSend(0xff); // dummy crc
  459. status_ = spiRec();
  460. if ((status_ & DATA_RES_MASK) != DATA_RES_ACCEPTED) {
  461. return false; // SD_CARD_ERROR_WRITE
  462. }
  463. return true;
  464. }