Arduino FatFS
Loading...
Searching...
No Matches
ArduinoSpiIO.h
1
18// This code was ported by kiwih from a copywrited (C) library written by ChaN
19// available at http://elm-chan.org/fsw/ff/ffsample.zip
20//(text at http://elm-chan.org/fsw/ff/00index_e.html)
21
22// This file provides the FatFs driver functions and SPI code required to manage
23// an SPI-connected MMC or compatible SD card with FAT
24
25// It is designed to be wrapped by a cubemx generated user_diskio.c file.
26
27#pragma once
28
29#include "BaseIO.h"
30#include "SPI.h"
31#include "sdcommon.h"
32
33
34namespace fatfs {
35
41class ArduinoSpiIO : public BaseIO {
42 public:
43 ArduinoSpiIO(int cs = -1, SPIClass &spi = SPI) { setSPI(cs, spi); }
44 ArduinoSpiIO(SPIClass &spi) { setSPI(spi); }
45
46 void setSPI(SPIClass &spi = SPI) {
47 this->p_spi = &spi;
48 this->cs = -1;
49 }
50
51 void setSPI(int cs = -1, SPIClass &spi = SPI) {
52 this->p_spi = &spi;
53 this->cs = cs;
54 if (cs != -1) {
55 pinMode(cs, OUTPUT);
56 }
57 }
58
59 DSTATUS disk_initialize(BYTE drv /* Physical drive number (0) */
60 ) override {
61 BYTE n, cmd, ty, ocr[4];
62
63 if (drv != 0) return STA_NOINIT; /* Supports only drive 0 */
64 // assume SPI already init init_spi(); /* Initialize SPI */
65
66 if (stat & STA_NODISK) return stat; /* Is card existing in the soket? */
67
68 set_spi_fast(false);
69 for (n = 10; n; n--) xchg_spi(0xFF); /* Send 80 dummy clocks */
70
71 ty = 0;
72 if (send_cmd(CMD0, 0) == 1) { /* Put the card SPI/Idle state */
73 spi_timer_on(1000); /* Initialization timeout = 1 sec */
74 if (send_cmd(CMD8, 0x1AA) == 1) { /* SDv2? */
75 for (n = 0; n < 4; n++)
76 ocr[n] = xchg_spi(0xFF); /* Get 32 bit return value of R7 resp */
77 if (ocr[2] == 0x01 &&
78 ocr[3] == 0xAA) { /* Is the card supports vcc of 2.7-3.6V? */
79 while (spi_timer_status() &&
80 send_cmd(ACMD41, 1UL << 30)); /* Wait for end of initialization
81 with ACMD41(HCS) */
82 if (spi_timer_status() &&
83 send_cmd(CMD58, 0) == 0) { /* Check CCS bit in the OCR */
84 for (n = 0; n < 4; n++) ocr[n] = xchg_spi(0xFF);
85 ty =
86 (ocr[0] & 0x40) ? CT_SD2 | CT_BLOCK : CT_SD2; /* Card id SDv2 */
87 }
88 }
89 } else { /* Not SDv2 card */
90 if (send_cmd(ACMD41, 0) <= 1) { /* SDv1 or MMC? */
91 ty = CT_SD1;
92 cmd = ACMD41; /* SDv1 (ACMD41(0)) */
93 } else {
94 ty = CT_MMC;
95 cmd = CMD1; /* MMCv3 (CMD1(0)) */
96 }
97 while (spi_timer_status() &&
98 send_cmd(cmd, 0)); /* Wait for end of initialization */
99 if (!spi_timer_status() ||
100 send_cmd(CMD16, 512) != 0) /* Set block length: 512 */
101 ty = 0;
102 }
103 }
104 CardType = ty; /* Card type */
105 despiselect();
106
107 if (ty) { /* OK */
108 set_spi_fast(true); /* Set fast clock */
109 stat = STA_CLEAR; /* Clear STA_NOINIT flag */
110 } else { /* Failed */
111 stat = STA_NOINIT;
112 }
113
114 return stat;
115 }
116
117 /*-----------------------------------------------------------------------*/
118 /* Get disk status */
119 /*-----------------------------------------------------------------------*/
120
121 DSTATUS disk_status(BYTE drv /* Physical drive number (0) */
122 ) override {
123 if (drv) return STA_NOINIT; /* Supports only drive 0 */
124 return stat; /* Return disk status */
125 }
126
127 /*-----------------------------------------------------------------------*/
128 /* Read sector(s) */
129 /*-----------------------------------------------------------------------*/
130
131 DRESULT disk_read(
132 BYTE drv, /* Physical drive number (0) */
133 BYTE *buff, /* Pointer to the data buffer to store read data */
134 DWORD sector, /* Start sector number (LBA) */
135 UINT count /* Number of sectors to read (1..128) */
136 ) override {
137 if (drv || !count) return RES_PARERR; /* Check parameter */
138 if (stat & STA_NOINIT) return RES_NOTRDY; /* Check if drive is ready */
139
140 if (!(CardType & CT_BLOCK))
141 sector *= 512; /* LBA ot BA conversion (byte addressing cards) */
142
143 if (count == 1) { /* Single sector read */
144 if ((send_cmd(CMD17, sector) == 0) /* READ_SINGLE_BLOCK */
145 && rcvr_datablock(buff, 512)) {
146 count = 0;
147 }
148 } else { /* Multiple sector read */
149 if (send_cmd(CMD18, sector) == 0) { /* READ_MULTIPLE_BLOCK */
150 do {
151 if (!rcvr_datablock(buff, 512)) break;
152 buff += 512;
153 } while (--count);
154 send_cmd(CMD12, 0); /* STOP_TRANSMISSION */
155 wait_ready(500); /* Wait for card to be ready after stop transmission */
156 }
157 }
158 despiselect();
159
160 return count ? RES_ERROR : RES_OK; /* Return result */
161 }
162
163 /*-----------------------------------------------------------------------*/
164 /* Write sector(s) */
165 /*-----------------------------------------------------------------------*/
166
167#if FF_IO_USE_WRITE
168
169 DRESULT disk_write(BYTE drv, /* Physical drive number (0) */
170 const BYTE *buff, /* Ponter to the data to write */
171 LBA_t sector, /* Start sector number (LBA) */
172 UINT count /* Number of sectors to write (1..128) */
173 ) override {
174 if (drv || !count) return RES_PARERR; /* Check parameter */
175 if (stat & STA_NOINIT) return RES_NOTRDY; /* Check drive status */
176 if (stat & STA_PROTECT) return RES_WRPRT; /* Check write protect */
177
178 if (!(CardType & CT_BLOCK))
179 sector *= 512; /* LBA ==> BA conversion (byte addressing cards) */
180
181 if (count == 1) { /* Single sector write */
182 if ((send_cmd(CMD24, sector) == 0) /* WRITE_BLOCK */
183 && xmit_datablock((BYTE*)buff, 0xFE)) {
184 count = 0;
185 }
186 } else { /* Multiple sector write */
187 if (CardType & CT_SDC)
188 send_cmd(ACMD23, count); /* Predefine number of sectors */
189 if (send_cmd(CMD25, sector) == 0) { /* WRITE_MULTIPLE_BLOCK */
190 do {
191 if (!xmit_datablock((BYTE*)buff, 0xFC)) break;
192 buff += 512;
193 } while (--count);
194 if (!xmit_datablock(0, 0xFD)) count = 1; /* STOP_TRAN token */
195 }
196 }
197 despiselect();
198
199 return count ? RES_ERROR : RES_OK; /* Return result */
200 }
201#endif
202
203 /*-----------------------------------------------------------------------*/
204 /* Miscellaneous drive controls other than data read/write */
205 /*-----------------------------------------------------------------------*/
206
207#if FF_IO_USE_IOCTL
208 DRESULT disk_ioctl(BYTE drv, /* Physical drive number (0) */
209 ioctl_cmd_t cmd, /* Control command code */
210 void *buff /* Pointer to the conrtol data */
211 ) override {
212 DRESULT res;
213 BYTE n, csd[16];
214 DWORD *dp, st, ed, csize;
215
216 if (drv) return RES_PARERR; /* Check parameter */
217 if (stat & STA_NOINIT) return RES_NOTRDY; /* Check if drive is ready */
218
219 res = RES_ERROR;
220
221 switch (cmd) {
222 case CTRL_SYNC: /* Wait for end of internal write process of the drive */
223 if (spiselect()) res = RES_OK;
224 break;
225
226 case GET_SECTOR_COUNT: /* Get drive capacity in unit of sector (DWORD) */
227 if ((send_cmd(CMD9, 0) == 0) && rcvr_datablock(csd, 16)) {
228 if ((csd[0] >> 6) == 1) { /* SDC ver 2.00 */
229 csize =
230 csd[9] + ((WORD)csd[8] << 8) + ((DWORD)(csd[7] & 63) << 16) + 1;
231 *(DWORD *)buff = csize << 10;
232 } else { /* SDC ver 1.XX or MMC ver 3 */
233 n = (csd[5] & 15) + ((csd[10] & 128) >> 7) + ((csd[9] & 3) << 1) +
234 2;
235 csize = (csd[8] >> 6) + ((WORD)csd[7] << 2) +
236 ((WORD)(csd[6] & 3) << 10) + 1;
237 *(DWORD *)buff = csize << (n - 9);
238 }
239 res = RES_OK;
240 }
241 break;
242
243 case GET_BLOCK_SIZE: /* Get erase block size in unit of sector (DWORD) */
244 if (CardType & CT_SD2) { /* SDC ver 2.00 */
245 if (send_cmd(ACMD13, 0) == 0) { /* Read SD status */
246 xchg_spi(0xFF);
247 if (rcvr_datablock(csd, 16)) { /* Read partial block */
248 for (n = 64 - 16; n; n--)
249 xchg_spi(0xFF); /* Purge trailing data */
250 *(DWORD *)buff = 16UL << (csd[10] >> 4);
251 res = RES_OK;
252 }
253 }
254 } else { /* SDC ver 1.XX or MMC */
255 if ((send_cmd(CMD9, 0) == 0) &&
256 rcvr_datablock(csd, 16)) { /* Read CSD */
257 if (CardType & CT_SD1) { /* SDC ver 1.XX */
258 *(DWORD *)buff =
259 (((csd[10] & 63) << 1) + ((WORD)(csd[11] & 128) >> 7) + 1)
260 << ((csd[13] >> 6) - 1);
261 } else { /* MMC */
262 *(DWORD *)buff =
263 ((WORD)((csd[10] & 124) >> 2) + 1) *
264 (((csd[11] & 3) << 3) + ((csd[11] & 224) >> 5) + 1);
265 }
266 res = RES_OK;
267 }
268 }
269 break;
270
271 case CTRL_TRIM: /* Erase a block of sectors (used when _USE_ERASE ==
272 1) */
273 if (!(CardType & CT_SDC)) break; /* Check if the card is SDC */
274 if (disk_ioctl(drv, MMC_GET_CSD, csd)) break; /* Get CSD */
275 if (!(csd[0] >> 6) && !(csd[10] & 0x40))
276 break; /* Check if sector erase can be applied to the card */
277 dp = (DWORD *)buff;
278 st = dp[0];
279 ed = dp[1]; /* Load sector block */
280 if (!(CardType & CT_BLOCK)) {
281 st *= 512;
282 ed *= 512;
283 }
284 if (send_cmd(CMD32, st) == 0 && send_cmd(CMD33, ed) == 0 &&
285 send_cmd(CMD38, 0) == 0 &&
286 wait_ready(30000)) { /* Erase sector block */
287 res = RES_OK; /* FatFs does not check result of this command */
288 }
289 break;
290
291 default:
292 res = RES_PARERR;
293 }
294
295 despiselect();
296
297 return res;
298 }
299
300#endif
301
302 protected:
303 volatile DSTATUS stat = STA_NOINIT; /* Physical drive status */
304 BYTE CardType; /* Card type flags */
305 SPIClass *p_spi = &SPI;
306 SPISettings spi_slow{280000, MSBFIRST, SPI_MODE0};
307 SPISettings spi_fast{FF_SPI_SPEED_FAST, MSBFIRST, SPI_MODE0};
308 SPISettings spi_settings;
309 uint32_t spi_timeout;
310 int cs = -1;
311
312 void spi_timer_on(uint32_t waitTicks) { spi_timeout = millis() + waitTicks; }
313
314 bool spi_timer_status() { return (millis() < spi_timeout); }
315
317 void set_spi_fast(bool fast) { spi_settings = fast ? spi_fast : spi_slow; }
318
320 inline void set_cs(bool high) {
321 if (cs != -1) digitalWrite(cs, high);
322 }
323
324 /* Exchange a byte */
325 inline BYTE xchg_spi(BYTE dat) { return p_spi->transfer(dat); }
326
327 /* Receive multiple byte */
328 void rcvr_spi_multi(BYTE *buff, UINT btr) {
329 // For receiving from SD card, send 0xFF dummy bytes while reading
330 for (UINT i = 0; i < btr; i++) {
331 buff[i] = xchg_spi(0xFF);
332 }
333 }
334
335 /* Send multiple bytes */
336 void xmit_spi_multi(BYTE *buff, UINT btr) {
337 p_spi->transfer(buff, btr);
338 }
339
340 /* Wait for card ready */
341 int wait_ready( /* 1:Ready, 0:Timeout */
342 UINT wt /* Timeout [ms] */
343 ) {
344 BYTE d;
345 // wait_ready needs its own timer, unfortunately, so it can't use the
346 // spi_timer functions
347 uint32_t timeout = millis() + wt;
348 do {
349 d = xchg_spi(0xFF);
350 /* This loop takes a time. Insert rot_rdq() here for multitask
351 * envilonment. */
352 /* Wait for card goes ready or timeout */
353 } while (d != 0xFF && ((millis() < timeout)));
354
355 return (d == 0xFF) ? 1 : 0;
356 }
357
358 /* Despiselect card and release SPI */
359
360 void despiselect(void) {
361 p_spi->endTransaction();
362 set_cs(true); /* Set CS# high */
363 xchg_spi(0xFF); /* Dummy clock (force DO hi-z for multiple slave SPI) */
364 }
365
366 /* Select card and wait for ready */
367
368 int spiselect(void) /* 1:OK, 0:Timeout */
369 {
370 p_spi->beginTransaction(spi_settings);
371 set_cs(false); /* Set CS# low */
372 xchg_spi(0xFF); /* Dummy clock (force DO enabled) */
373 if (wait_ready(500)) return 1; /* Wait for card ready */
374
375 despiselect();
376 return 0; /* Timeout */
377 }
378
379 /* Receive a data packet from the MMC */
380
381 int rcvr_datablock( /* 1:OK, 0:Error */
382 BYTE *buff, /* Data buffer */
383 UINT btr /* Data block length (byte) */
384 ) {
385 BYTE token;
386
387 uint64_t end = millis() + 200;
388 do { /* Wait for DataStart token in timeout of 200ms */
389 token = xchg_spi(0xFF);
390 /* This loop will take a time. Insert rot_rdq() here for multitask
391 * envilonment. */
392 } while ((token == 0xFF) && millis() < end);
393 if (token != 0xFE)
394 return 0; /* Function fails if invalid DataStart token or timeout */
395
396 rcvr_spi_multi(buff, btr); /* Receive data from card */
397 xchg_spi(0xFF);
398 xchg_spi(0xFF); /* Discard CRC */
399
400 return 1; /* Function succeeded */
401 }
402
403 /* Send a data packet to the MMC */
404
405#if FF_IO_USE_WRITE
406 int xmit_datablock( /* 1:OK, 0:Failed */
407 BYTE *buff, /* Ponter to 512 byte data to be sent */
408 BYTE token /* Token */
409 ) {
410 BYTE resp;
411
412 if (!wait_ready(500)) return 0; /* Wait for card ready */
413
414 xchg_spi(token); /* Send token */
415 if (token != 0xFD) { /* Send data if token is other than StopTran */
416 xmit_spi_multi(buff, 512); /* Data */
417 xchg_spi(0xFF);
418 xchg_spi(0xFF); /* Dummy CRC */
419
420 resp = xchg_spi(0xFF); /* Receive data resp */
421 if ((resp & 0x1F) != 0x05)
422 return 0; /* Function fails if the data packet was not accepted */
423 }
424 return 1;
425 }
426#endif
427
428 /* Send a command packet to the MMC */
429 BYTE send_cmd( /* Return value: R1 resp (bit7==1:Failed to send) */
430 BYTE cmd, /* Command index */
431 DWORD arg /* Argument */
432 ) {
433 BYTE n, res;
434
435 if (cmd & 0x80) { /* Send a CMD55 prior to ACMD<n> */
436 cmd &= 0x7F;
437 res = send_cmd(CMD55, 0);
438 if (res > 1) return res;
439 }
440
441 /* Select the card and wait for ready except to stop multiple block read */
442 if (cmd != CMD12) {
443 despiselect();
444 if (!spiselect()) return 0xFF;
445 }
446
447 /* Send command packet */
448 xchg_spi(0x40 | cmd); /* Start + command index */
449 xchg_spi((BYTE)(arg >> 24)); /* Argument[31..24] */
450 xchg_spi((BYTE)(arg >> 16)); /* Argument[23..16] */
451 xchg_spi((BYTE)(arg >> 8)); /* Argument[15..8] */
452 xchg_spi((BYTE)arg); /* Argument[7..0] */
453 n = 0x01; /* Dummy CRC + Stop */
454 if (cmd == CMD0) n = 0x95; /* Valid CRC for CMD0(0) */
455 if (cmd == CMD8) n = 0x87; /* Valid CRC for CMD8(0x1AA) */
456 xchg_spi(n);
457
458 /* Receive command resp */
459 if (cmd == CMD12)
460 xchg_spi(0xFF); /* Diacard following one byte when CMD12 */
461 n = 10; /* Wait for response (10 bytes max) */
462 do {
463 res = xchg_spi(0xFF);
464 } while ((res & 0x80) && --n);
465
466 return res; /* Return received response */
467 }
468};
469
470} // namespace fatfs
Accessing a SD card via the Arduino SPI API.
Definition ArduinoSpiIO.h:41
void set_cs(bool high)
update the CS pin
Definition ArduinoSpiIO.h:320
void set_spi_fast(bool fast)
set fast/slow SPI speed
Definition ArduinoSpiIO.h:317
Empty IO implementation that we can use to test the compilation.
Definition BaseIO.h:10