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.

528 line
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. // 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.
  204. */
  205. uint8_t Sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin) {
  206. type_ = 0;
  207. chipSelectPin_ = chipSelectPin;
  208. // 16-bit init start time allows over a minute
  209. uint16_t t0 = (uint16_t)millis();
  210. uint32_t arg;
  211. digitalWrite(chipSelectPin_, HIGH);
  212. pinMode(chipSelectPin_, OUTPUT);
  213. digitalWrite(chipSelectPin_, HIGH);
  214. #ifdef USE_TEENSY3_SPI
  215. spiBegin();
  216. spiInit(6);
  217. #else
  218. // set pin modes
  219. pinMode(SPI_MISO_PIN, INPUT);
  220. pinMode(SPI_MOSI_PIN, OUTPUT);
  221. pinMode(SPI_SCK_PIN, OUTPUT);
  222. // SS must be in output mode even it is not chip select
  223. pinMode(SS_PIN, OUTPUT);
  224. digitalWrite(SS_PIN, HIGH); // disable any SPI device using hardware SS pin
  225. // Enable SPI, Master, clock rate f_osc/128
  226. SPCR = (1 << SPE) | (1 << MSTR) | (1 << SPR1) | (1 << SPR0);
  227. // clear double speed
  228. SPSR &= ~(1 << SPI2X);
  229. #ifdef SPI_HAS_TRANSACTION
  230. settings = SPISettings(250000, MSBFIRST, SPI_MODE0);
  231. #endif
  232. #endif // not USE_TEENSY3_SPI
  233. // must supply min of 74 clock cycles with CS high.
  234. #ifdef SPI_HAS_TRANSACTION
  235. SPI.beginTransaction(settings);
  236. #endif
  237. for (uint8_t i = 0; i < 10; i++) spiSend(0XFF);
  238. #ifdef SPI_HAS_TRANSACTION
  239. SPI.endTransaction();
  240. #endif
  241. chipSelectLow();
  242. // command to go idle in SPI mode
  243. while ((status_ = cardCommand(CMD0, 0)) != R1_IDLE_STATE) {
  244. if (((uint16_t)(millis() - t0)) > SD_INIT_TIMEOUT) {
  245. goto fail; // SD_CARD_ERROR_CMD0
  246. }
  247. }
  248. // check SD version
  249. if ((cardCommand(CMD8, 0x1AA) & R1_ILLEGAL_COMMAND)) {
  250. type(SD_CARD_TYPE_SD1);
  251. } else {
  252. // only need last byte of r7 response
  253. for (uint8_t i = 0; i < 4; i++) status_ = spiRec();
  254. if (status_ != 0XAA) {
  255. goto fail; // SD_CARD_ERROR_CMD8
  256. }
  257. type(SD_CARD_TYPE_SD2);
  258. }
  259. // initialize card and send host supports SDHC if SD2
  260. arg = type() == SD_CARD_TYPE_SD2 ? 0X40000000 : 0;
  261. while ((status_ = cardAcmd(ACMD41, arg)) != R1_READY_STATE) {
  262. // check for timeout
  263. if (((uint16_t)(millis() - t0)) > 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::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. if (cardCommand(CMD17, block)) {
  296. goto fail; // SD_CARD_ERROR_CMD17
  297. }
  298. if (!waitStartBlock()) {
  299. goto fail;
  300. }
  301. #ifdef USE_TEENSY3_SPI
  302. spiRec(dst, 512);
  303. spiRecIgnore(2);
  304. #else // OPTIMIZE_HARDWARE_SPI
  305. // start first spi transfer
  306. SPDR = 0XFF;
  307. // transfer data
  308. for (uint16_t i = 0; i < 511; i++) {
  309. while (!(SPSR & (1 << SPIF)));
  310. dst[i] = SPDR;
  311. SPDR = 0XFF;
  312. }
  313. // wait for last byte
  314. while (!(SPSR & (1 << SPIF)));
  315. dst[511] = SPDR;
  316. // skip CRC bytes
  317. spiRec();
  318. spiRec();
  319. #endif
  320. chipSelectHigh();
  321. return true;
  322. fail:
  323. chipSelectHigh();
  324. return false;
  325. }
  326. //------------------------------------------------------------------------------
  327. /** read CID or CSR register */
  328. uint8_t Sd2Card::readRegister(uint8_t cmd, void* buf) {
  329. uint8_t* dst = reinterpret_cast<uint8_t*>(buf);
  330. if (cardCommand(cmd, 0)) {
  331. goto fail; // SD_CARD_ERROR_READ_REG
  332. }
  333. if (!waitStartBlock()) goto fail;
  334. // transfer data
  335. for (uint16_t i = 0; i < 16; i++) dst[i] = spiRec();
  336. spiRec(); // get first crc byte
  337. spiRec(); // get second crc byte
  338. chipSelectHigh();
  339. return true;
  340. fail:
  341. chipSelectHigh();
  342. return false;
  343. }
  344. //------------------------------------------------------------------------------
  345. /**
  346. * Set the SPI clock rate.
  347. *
  348. * \param[in] sckRateID A value in the range [0, 6].
  349. *
  350. * 0 = 8 MHz
  351. * 1 = 4 MHz
  352. * 2 = 2 MHz
  353. * 3 = 1 MHz
  354. * 4 = 500 kHz
  355. * 5 = 125 kHz
  356. * 6 = 63 kHz
  357. *
  358. * The SPI clock will be set to F_CPU/pow(2, 1 + sckRateID). The maximum
  359. * SPI rate is F_CPU/2 for \a sckRateID = 0 and the minimum rate is F_CPU/128
  360. * for \a scsRateID = 6.
  361. *
  362. * \return The value one, true, is returned for success and the value zero,
  363. * false, is returned for an invalid value of \a sckRateID.
  364. */
  365. uint8_t Sd2Card::setSckRate(uint8_t sckRateID) {
  366. #ifdef USE_TEENSY3_SPI
  367. spiInit(sckRateID);
  368. return true;
  369. #else
  370. if (sckRateID > 6) sckRateID = 6;
  371. // see avr processor datasheet for SPI register bit definitions
  372. if ((sckRateID & 1) || sckRateID == 6) {
  373. SPSR &= ~(1 << SPI2X);
  374. } else {
  375. SPSR |= (1 << SPI2X);
  376. }
  377. SPCR &= ~((1 <<SPR1) | (1 << SPR0));
  378. SPCR |= (sckRateID & 4 ? (1 << SPR1) : 0)
  379. | (sckRateID & 2 ? (1 << SPR0) : 0);
  380. #ifdef SPI_HAS_TRANSACTION
  381. switch (sckRateID) {
  382. case 0: settings = SPISettings(8000000, MSBFIRST, SPI_MODE0); break;
  383. case 1: settings = SPISettings(4000000, MSBFIRST, SPI_MODE0); break;
  384. case 2: settings = SPISettings(2000000, MSBFIRST, SPI_MODE0); break;
  385. case 3: settings = SPISettings(1000000, MSBFIRST, SPI_MODE0); break;
  386. case 4: settings = SPISettings(500000, MSBFIRST, SPI_MODE0); break;
  387. case 5: settings = SPISettings(250000, MSBFIRST, SPI_MODE0); break;
  388. default: settings = SPISettings(125000, MSBFIRST, SPI_MODE0);
  389. }
  390. #endif
  391. return true;
  392. #endif
  393. }
  394. //------------------------------------------------------------------------------
  395. // wait for card to go not busy
  396. uint8_t Sd2Card::waitNotBusy(uint16_t timeoutMillis) {
  397. uint16_t t0 = millis();
  398. do {
  399. if (spiRec() == 0XFF) return true;
  400. }
  401. while (((uint16_t)millis() - t0) < timeoutMillis);
  402. return false;
  403. }
  404. //------------------------------------------------------------------------------
  405. /** Wait for start block token */
  406. uint8_t Sd2Card::waitStartBlock(void) {
  407. uint16_t t0 = millis();
  408. while ((status_ = spiRec()) == 0XFF) {
  409. if (((uint16_t)millis() - t0) > SD_READ_TIMEOUT) {
  410. return false; // SD_CARD_ERROR_READ_TIMEOUT
  411. }
  412. }
  413. if (status_ != DATA_START_BLOCK) {
  414. return false; // SD_CARD_ERROR_READ
  415. }
  416. return true;
  417. }
  418. //------------------------------------------------------------------------------
  419. /**
  420. * Writes a 512 byte block to an SD card.
  421. *
  422. * \param[in] blockNumber Logical block to be written.
  423. * \param[in] src Pointer to the location of the data to be written.
  424. * \return The value one, true, is returned for success and
  425. * the value zero, false, is returned for failure.
  426. */
  427. uint8_t Sd2Card::writeBlock(uint32_t blockNumber, const uint8_t* src) {
  428. #if SD_PROTECT_BLOCK_ZERO
  429. // don't allow write to first block
  430. if (blockNumber == 0) {
  431. goto fail; // SD_CARD_ERROR_WRITE_BLOCK_ZERO
  432. }
  433. #endif // SD_PROTECT_BLOCK_ZERO
  434. // use address if not SDHC card
  435. if (type() != SD_CARD_TYPE_SDHC) blockNumber <<= 9;
  436. if (cardCommand(CMD24, blockNumber)) {
  437. goto fail; // SD_CARD_ERROR_CMD24
  438. }
  439. if (!writeData(DATA_START_BLOCK, src)) goto fail;
  440. // wait for flash programming to complete
  441. if (!waitNotBusy(SD_WRITE_TIMEOUT)) {
  442. goto fail; // SD_CARD_ERROR_WRITE_TIMEOUT
  443. }
  444. // response is r2 so get and check two bytes for nonzero
  445. if (cardCommand(CMD13, 0) || spiRec()) {
  446. goto fail; // SD_CARD_ERROR_WRITE_PROGRAMMING
  447. }
  448. chipSelectHigh();
  449. return true;
  450. fail:
  451. chipSelectHigh();
  452. return false;
  453. }
  454. //------------------------------------------------------------------------------
  455. // send one block of data for write block or write multiple blocks
  456. uint8_t Sd2Card::writeData(uint8_t token, const uint8_t* src) {
  457. #ifdef OPTIMIZE_HARDWARE_SPI
  458. // send data - optimized loop
  459. SPDR = token;
  460. // send two byte per iteration
  461. for (uint16_t i = 0; i < 512; i += 2) {
  462. while (!(SPSR & (1 << SPIF)));
  463. SPDR = src[i];
  464. while (!(SPSR & (1 << SPIF)));
  465. SPDR = src[i+1];
  466. }
  467. // wait for last data byte
  468. while (!(SPSR & (1 << SPIF)));
  469. #else // OPTIMIZE_HARDWARE_SPI
  470. spiSend(token);
  471. for (uint16_t i = 0; i < 512; i++) {
  472. spiSend(src[i]);
  473. }
  474. #endif // OPTIMIZE_HARDWARE_SPI
  475. spiSend(0xff); // dummy crc
  476. spiSend(0xff); // dummy crc
  477. status_ = spiRec();
  478. if ((status_ & DATA_RES_MASK) != DATA_RES_ACCEPTED) {
  479. chipSelectHigh();
  480. return false; // SD_CARD_ERROR_WRITE
  481. }
  482. return true;
  483. }