1 /* mbed USBMSD_SD Library, for providing file access to SD cards
2 * Copyright (c) 2008-2010, sford
4 * Permission is hereby granted, free of charge, to any person obtaining a copy
5 * of this software and associated documentation files (the "Software"), to deal
6 * in the Software without restriction, including without limitation the rights
7 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 * copies of the Software, and to permit persons to whom the Software is
9 * furnished to do so, subject to the following conditions:
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 * SD and MMC cards support a number of interfaces, but common to them all
26 * is one based on SPI. This is the one I'm implmenting because it means
27 * it is much more portable even though not so performant, and we already
28 * have the mbed SPI Interface!
30 * The main reference I'm using is Chapter 7, "SPI Mode" of:
31 * http://www.sdcard.org/developers/tech/sdcard/pls/Simplified_Physical_Layer_Spec.pdf
35 * The SD card powers up in SD mode. The SPI interface mode is selected by
36 * asserting CS low and sending the reset command (CMD0). The card will
37 * respond with a (R1) response.
39 * CMD8 is optionally sent to determine the voltage range supported, and
40 * indirectly determine whether it is a version 1.x SD/non-SD card or
41 * version 2.x. I'll just ignore this for now.
43 * ACMD41 is repeatedly issued to initialise the card, until "in idle"
44 * (bit 0) of the R1 response goes to '0', indicating it is initialised.
46 * You should also indicate whether the host supports High Capicity cards,
47 * and check whether the card is high capacity - i'll also ignore this
51 * The SD SPI protocol is based on transactions made up of 8-bit words, with
52 * the host starting every bus transaction by asserting the CS signal low. The
53 * card always responds to commands, data blocks and errors.
55 * The protocol supports a CRC, but by default it is off (except for the
56 * first reset CMD0, where the CRC can just be pre-calculated, and CMD8)
57 * I'll leave the CRC off I think!
59 * Standard capacity cards have variable data block sizes, whereas High
60 * Capacity cards fix the size of data block to 512 bytes. I'll therefore
61 * just always use the Standard Capacity cards with a block size of 512 bytes.
62 * This is set with CMD16.
64 * You can read and write single blocks (CMD17, CMD25) or multiple blocks
65 * (CMD18, CMD25). For simplicity, I'll just use single block accesses. When
66 * the card gets a read command, it responds with a response token, and then
67 * a data token or an error.
71 * Commands are 6-bytes long, containing the command, 32-bit argument, and CRC.
73 * +---------------+------------+------------+-----------+----------+--------------+
74 * | 01 | cmd[5:0] | arg[31:24] | arg[23:16] | arg[15:8] | arg[7:0] | crc[6:0] | 1 |
75 * +---------------+------------+------------+-----------+----------+--------------+
77 * As I'm not using CRC, I can fix that byte to what is needed for CMD0 (0x95)
79 * All Application Specific commands shall be preceded with APP_CMD (CMD55).
83 * The main response format (R1) is a status byte (normally zero). Key flags:
84 * idle - 1 if the card is in an idle state/initialising
85 * cmd - 1 if an illegal command code was detected
87 * +-------------------------------------------------+
88 * R1 | 0 | arg | addr | seq | crc | cmd | erase | idle |
89 * +-------------------------------------------------+
91 * R1b is the same, except it is followed by a busy signal (zeros) until
92 * the first non-zero byte when it is ready again.
96 * Every data block written to the card is acknowledged by a byte
99 * +----------------------+
100 * | xxx | 0 | status | 1 |
101 * +----------------------+
106 * Single Block Read and Write
107 * ---------------------------
109 * Block transfers have a byte header, followed by the data, followed
110 * by a 16-bit CRC. In our case, the data will always be 512 bytes.
112 * +------+---------+---------+- - - -+---------+-----------+----------+
113 * | 0xFE | data[0] | data[1] | | data[n] | crc[15:8] | crc[7:0] |
114 * +------+---------+---------+- - - -+---------+-----------+----------+
117 #include "USBMSD_SD.h"
119 #define SD_COMMAND_TIMEOUT 5000
121 USBMSD_SD::USBMSD_SD(PinName mosi
, PinName miso
, PinName sclk
, PinName cs
) :
122 _spi(mosi
, miso
, sclk
), _cs(cs
) {
129 #define R1_IDLE_STATE (1 << 0)
130 #define R1_ERASE_RESET (1 << 1)
131 #define R1_ILLEGAL_COMMAND (1 << 2)
132 #define R1_COM_CRC_ERROR (1 << 3)
133 #define R1_ERASE_SEQUENCE_ERROR (1 << 4)
134 #define R1_ADDRESS_ERROR (1 << 5)
135 #define R1_PARAMETER_ERROR (1 << 6)
138 // - v1.x Standard Capacity
139 // - v2.x Standard Capacity
140 // - v2.x High Capacity
141 // - Not recognised as an SD Card
143 #define SDCARD_FAIL 0
146 #define SDCARD_V2HC 3
148 int USBMSD_SD::initialise_card() {
149 // Set to 100kHz for initialisation, and clock card with cs = 1
150 _spi
.frequency(100000);
152 for(int i
=0; i
<16; i
++) {
156 // send CMD0, should return with all zeros except IDLE STATE set (bit 0)
157 if(_cmd(0, 0) != R1_IDLE_STATE
) {
158 fprintf(stderr
, "No disk, or could not put SD card in to SPI idle state\n");
162 // send CMD8 to determine whther it is ver 2.x
164 if(r
== R1_IDLE_STATE
) {
165 return initialise_card_v2();
166 } else if(r
== (R1_IDLE_STATE
| R1_ILLEGAL_COMMAND
)) {
167 return initialise_card_v1();
169 fprintf(stderr
, "Not in idle state after sending CMD8 (not an SD card?)\n");
174 int USBMSD_SD::initialise_card_v1() {
175 for(int i
=0; i
<SD_COMMAND_TIMEOUT
; i
++) {
177 if(_cmd(41, 0) == 0) {
182 fprintf(stderr
, "Timeout waiting for v1.x card\n");
186 int USBMSD_SD::initialise_card_v2() {
188 for(int i
=0; i
<SD_COMMAND_TIMEOUT
; i
++) {
190 if(_cmd(41, 0) == 0) {
196 fprintf(stderr
, "Timeout waiting for v2.x card\n");
200 int USBMSD_SD::disk_initialize() {
202 int i
= initialise_card();
203 // printf("init card = %d\n", i);
206 _sectors
= _sd_sectors();
208 // Set block length to 512 (CMD16)
209 if(_cmd(16, 512) != 0) {
210 fprintf(stderr
, "Set 512-byte block timed out\n");
214 _spi
.frequency(5000000); // Set to 5MHz for data transfer
220 int USBMSD_SD::disk_write(const char *buffer
, int block_number
) {
221 // set write address for single block (CMD24)
222 if(_cmd(24, block_number
* 512) != 0) {
226 // send the data block
231 int USBMSD_SD::disk_read(char *buffer
, int block_number
) {
232 // set read address for single block (CMD17)
233 if(_cmd(17, block_number
* 512) != 0) {
242 int USBMSD_SD::disk_status() { return _status
; }
243 int USBMSD_SD::disk_sync() { return 0; }
244 int USBMSD_SD::disk_sectors() { return _sectors
; }
248 int USBMSD_SD::_cmd(int cmd
, int arg
) {
252 _spi
.write(0x40 | cmd
);
253 _spi
.write(arg
>> 24);
254 _spi
.write(arg
>> 16);
255 _spi
.write(arg
>> 8);
256 _spi
.write(arg
>> 0);
259 // wait for the repsonse (response[7] == 0)
260 for(int i
=0; i
<SD_COMMAND_TIMEOUT
; i
++) {
261 int response
= _spi
.write(0xFF);
262 if(!(response
& 0x80)) {
270 return -1; // timeout
272 int USBMSD_SD::_cmdx(int cmd
, int arg
) {
276 _spi
.write(0x40 | cmd
);
277 _spi
.write(arg
>> 24);
278 _spi
.write(arg
>> 16);
279 _spi
.write(arg
>> 8);
280 _spi
.write(arg
>> 0);
283 // wait for the repsonse (response[7] == 0)
284 for(int i
=0; i
<SD_COMMAND_TIMEOUT
; i
++) {
285 int response
= _spi
.write(0xFF);
286 if(!(response
& 0x80)) {
292 return -1; // timeout
296 int USBMSD_SD::_cmd58() {
301 _spi
.write(0x40 | 58);
302 _spi
.write(arg
>> 24);
303 _spi
.write(arg
>> 16);
304 _spi
.write(arg
>> 8);
305 _spi
.write(arg
>> 0);
308 // wait for the repsonse (response[7] == 0)
309 for(int i
=0; i
<SD_COMMAND_TIMEOUT
; i
++) {
310 int response
= _spi
.write(0xFF);
311 if(!(response
& 0x80)) {
312 int ocr
= _spi
.write(0xFF) << 24;
313 ocr
|= _spi
.write(0xFF) << 16;
314 ocr
|= _spi
.write(0xFF) << 8;
315 ocr
|= _spi
.write(0xFF) << 0;
316 // printf("OCR = 0x%08X\n", ocr);
324 return -1; // timeout
327 int USBMSD_SD::_cmd8() {
331 _spi
.write(0x40 | 8); // CMD8
332 _spi
.write(0x00); // reserved
333 _spi
.write(0x00); // reserved
334 _spi
.write(0x01); // 3.3v
335 _spi
.write(0xAA); // check pattern
336 _spi
.write(0x87); // crc
338 // wait for the repsonse (response[7] == 0)
339 for(int i
=0; i
<SD_COMMAND_TIMEOUT
* 1000; i
++) {
341 response
[0] = _spi
.write(0xFF);
342 if(!(response
[0] & 0x80)) {
343 for(int j
=1; j
<5; j
++) {
344 response
[i
] = _spi
.write(0xFF);
353 return -1; // timeout
356 int USBMSD_SD::_read(char *buffer
, int length
) {
359 // read until start byte (0xFF)
360 while(_spi
.write(0xFF) != 0xFE);
363 for(int i
=0; i
<length
; i
++) {
364 buffer
[i
] = _spi
.write(0xFF);
366 _spi
.write(0xFF); // checksum
374 int USBMSD_SD::_write(const char *buffer
, int length
) {
377 // indicate start of block
381 for(int i
=0; i
<length
; i
++) {
382 _spi
.write(buffer
[i
]);
385 // write the checksum
389 // check the repsonse token
390 if((_spi
.write(0xFF) & 0x1F) != 0x05) {
396 // wait for write to finish
397 while(_spi
.write(0xFF) == 0);
404 static int ext_bits(char *data
, int msb
, int lsb
) {
406 int size
= 1 + msb
- lsb
;
407 for(int i
=0; i
<size
; i
++) {
408 int position
= lsb
+ i
;
409 int byte
= 15 - (position
>> 3);
410 int bit
= position
& 0x7;
411 int value
= (data
[byte
] >> bit
) & 1;
417 int USBMSD_SD::_sd_sectors() {
419 // CMD9, Response R2 (R1 byte + 16-byte block read)
420 if(_cmdx(9, 0) != 0) {
421 fprintf(stderr
, "Didn't get a response from the disk\n");
426 if(_read(csd
, 16) != 0) {
427 fprintf(stderr
, "Couldn't read csd response from disk\n");
431 // csd_structure : csd[127:126]
432 // c_size : csd[73:62]
433 // c_size_mult : csd[49:47]
434 // read_bl_len : csd[83:80] - the *maximum* read block length
436 int csd_structure
= ext_bits(csd
, 127, 126);
437 int c_size
= ext_bits(csd
, 73, 62);
438 int c_size_mult
= ext_bits(csd
, 49, 47);
439 int read_bl_len
= ext_bits(csd
, 83, 80);
441 // printf("CSD_STRUCT = %d\n", csd_structure);
443 if(csd_structure
!= 0) {
444 fprintf(stderr
, "This disk tastes funny! I only know about type 0 CSD structures\n");
448 // memory capacity = BLOCKNR * BLOCK_LEN
450 // BLOCKNR = (C_SIZE+1) * MULT
451 // MULT = 2^(C_SIZE_MULT+2) (C_SIZE_MULT < 8)
452 // BLOCK_LEN = 2^READ_BL_LEN, (READ_BL_LEN < 12)
454 int block_len
= 1 << read_bl_len
;
455 int mult
= 1 << (c_size_mult
+ 2);
456 int blocknr
= (c_size
+ 1) * mult
;
457 capacity
= blocknr
* block_len
;
459 int blocks
= capacity
/ 512;
465 int USBMSD_SD::disk_size() {