Está en la página 1de 15

Command Abbreviation Argument Response Description

CMD0 GO_IDLE_STATE None R1 Reset the SD card

CMD1 SEND_OP_COND None R1 Initialize card

CMD9 SEND_CSD None R1 Get CSD register data

CMD10 SEND_CID None R1 Get CID register data

CMD17 READ_SINGLE_BLOCK Data address (0:31) R1 Read a block of data

CMD24 WRITE_BLOCK Data address (0:31) R1 Write a block of data

FUENTE: ( http://m.eet.com/media/1114317/1515_ch3.pdf PAG 42)

Otros comandos fuente:


(https://drive.google.com/file/d/1IhBYfNMBtBTLjNc88J8VenbFwM8hc61xpnuec9-CrflFK-
id0VzbthIljGb3/view?pref=2&pli=1 )
1. Reset de la memoria comando 0 (CMD0)
2. Inicialización de la memoria comando 1 (CMD1)
3. Configuración del bloque de 512 bytes comando 16 (CMD16)
4. Escritura de un bloque de 512 bytes (CMD24)
5. Lectura de un bloque de 512 bytes comando 17 (CMD17)
´´La memoria SD debe responder con 0x00 para todos los comandos antes mencionados, pero
para el comando 0 (CMD0) la memoria responde con 0x01 debido a su estado inicial´´

Estado de reposo o busy (0x01), según la imagen de comandos y según (http://elm-


chan.org/docs/mmc/mmc_e.html)
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
Un pull-up en la DO patillas no puede ser omitido, o algunas tarjetas se producirá un
error al inicializar. (http://elm-chan.org/docs/mmc/mmc_e.html )
PASOS desde inicialización hasta cambio de protocolo a SPI de pic a
tarjeta SD:
POWER UP: (2.7 – 3.6 V) (img sdinit)… After supply voltage reached 2.2 volts, wait for
one millisecond at least. Set SPI clock rate between 100 kHz and 400 kHz. Set DI and
CS high and apply 74 or more clock pulses to SCLK. The card will enter its native
operating mode and go ready to accept native command.

--> Firstly, as mentioned by others, select a low initial clock rate (generally in the 100 kHz - 400
kHz range; use 400 kHz if possible); you'll be able to switch to higher clock later on, if the device
allows for it. While new cards can safely withstand MHz-ish clocking, older will complain (i.e.
not communicate or return garbage).

(http://electronics.stackexchange.com/questions/77417/what-is-the-correct-command-
sequence-for-microsd-card-initialization-in-spi )
En algunos referencias se advierte que es preciso una conexión inicial a baja velocidad (se cita
un máximo de 400Khz) y solo cuando la tarjeta ha sido convenientemente inicializada y ha
habido una negociación pasaremos a la velocidad máxima soportada. En otros lugares se indica
que dicha restricción es sólo para tarjetas MMC. Con las tarjetas que yo he probado (SD todas
ellas) la inicialización ha sido satisfactoria arrancando a la máxima velocidad, pero no cuesta
nada realizar el primer intercambio a velocidad baja y pasar a velocidad alta tras la inicialización.
( http://picfernalia.blogspot.com/2013/04/interfaz-con-tarjetas-sd-protocolo-spi.html )

PRIMER PASO: --Reseteamos la tarjeta y la ponemos en modo SPI, para ello pasamos la señal de
CS a 0 y enviamos el comando 0. Antes de empezar la especificación dice que hay que dar al
menos 74 pulsos al reloj (lo haremos enviando el código 0xFF(8bits) 10 veces, con lo que
damos 80 pulsos) . Repetimos el comando 0 hasta que la tarjeta pasa a estado IDLE.
(http://blog.deinventos.com/utilizar-una-sd-como-unidad-de-almacenamiento-para-pic-
programacion-basica/ )
--AFTER POWER UP THE SD CARD IS IN THE IDLE STATE. SENDING COMMAND CMD0 ALSO PUTS
THE CARD IN THE IDLE STATE. AT LEAST 74 CLOCK CYCLES SHOULD BE SENT TO THE CARD WITH
THE DATA OUT AND CS LINES SET TO LOGIC ´´1´´ BEFORE STARTING TO COMMUNICATE WITH
THE CARD. (http://m.eet.com/media/1114317/1515_ch3.pdf )
---Al iniciar la memoria se establece en modo SD. Para entrar en modo SPI se debe enviar el
comando CMD0 con el pin CS a 0V, si la memoria reconoce la petición de cambio de protocolo
responde con la respuesta R1 (0x01) como se ilustra en la figura 2.
---The SD Card wakes up in the SD Bus mode. It will enter SPI mode if the CS signal is asserted
(negative) during the reception of the reset command (CMD0).
(https://drive.google.com/file/d/1IhBYfNMBtBTLjNc88J8VenbFwM8hc61xpnuec9-CrflFK-
id0VzbthIljGb3/view?pref=2&pli=1 )
---THE SD CARD IS INITIALLY IN THE BUS MODE. IT WILL ENTER THE SPI MODE IF THE CS LINE IS
HELD LOW WHILE SENDING THE CMD0 COMMAND. WHEN THE CARD SWITCHES TO THE SPI
MODE, IT WILL RESPOND WITH THE SPI MODE R1 RESPONSE FORMAT.
( http://m.eet.com/media/1114317/1515_ch3.pdf )
SEGUNDO PASO:
(En estado de reposo(0x01), la tarjeta sólo acepta CMD0, CMD1, ACMD41, CMD58 y
CMD59.)
CHECK R1 RESPONSE TO MAKE SURE THERE ARE NO ERROR BITS SET
( http://m.eet.com/media/1114317/1515_ch3.pdf )
En el modo de SPI, la dirección de los datos en las líneas de señal están fijados y los datos se
transfieren en orientado a bytes de comunicación en serie. La trama de instrucción de un
huésped a la tarjeta es un paquete de longitud fija que se muestra a continuación. La tarjeta
está lista para recibir una trama de instrucción cuando se conduce DO alta. Después de una
trama de instrucción se envía a la tarjeta, una respuesta a la orden (R1, R2, R3 o R7) se envía de
nuevo de la tarjeta. Debido a que la transferencia de datos es impulsado por el reloj de serie
generada por el controlador de host, el controlador de host debe seguir para leer los datos,
enviar un 0xFF y obtener byte recibido, hasta que se detecta una respuesta válida. (Because
the data transfer is driven by serial clock generated by host controller, the host controller
must continue to read data, send a 0xFF and get received byte, until a valid response is
detected.)
When a command frame is transmitted to the card, a response to the command (R1, R2 or R3) will able
to be read from the card. (http://users.ece.utexas.edu/~valvano/EE345M/view12_SPI_SDC.pdf )
 La señal DI debe mantenerse alta durante la transferencia de lectura (enviar un 0xFF y obtener
los datos recibidos). La respuesta se envía de vuelta dentro de un tiempo de respuesta de
comando (NCR ), 0 a 8 bytes para SDC, de 1 a 8 bytes para MMC.
Following the sending of a command, there is a delay called the Card Response time (NCR)
which can take 1 to 8 bytes depending on the command (during this time the D-out line will be
high so FFh will be received by the host). The commands shown below have a one byte gap -
ideally you should read bytes until you get a valid card response. When sent, this card response
is normally a single byte (called "R1") with its MSB at 0. The rest of the bits have the
following meaning when set to 1:
"R1" bit: Signifies:
-----------------------------
6 - Parameter error
5 - Address error
4 - Erase sequence error
3 - Command CRC error
2 - Illegal command
1 - Erase reset
0 - In idle state
Therefore a response of 00h is normally desired.

When the CMD0 is accepted, the card will enter idle state and respond R1 response with In Idle State bit
(0x01).

A byte of response R1 is returned for most commands. The bit field of R1 response is shown in Figure
7, the value 0x00 means successful.
(http://users.ece.utexas.edu/~valvano/EE345M/view12_SPI_SDC.pdf )
(http://www.retroleum.co.uk/mmc_cards.html )
 INFORMACION IMPORTANTE: La señal CS debe ser conducido de mayor a menor antes de
enviar una trama de instrucción y la mantuvo baja durante la transacción (mando, la respuesta
y la transferencia de datos en caso de existir).  (The CS signal must be driven high to low prior to
send a command frame and held it low during the transaction (command, response and data
transfer if exist).) La función de CRC es opcional en el modo SPI. Campo CRC en la trama de
instrucción no está marcada por la tarjeta.

( http://elm-chan.org/docs/mmc/mmc_e.html )
The CS signal must be held low during a transaction (command, response and data transfer if exist).
(http://users.ece.utexas.edu/~valvano/EE345M/view12_SPI_SDC.pdf )
(The card checks the CS line when CMD0 is received and goes into SPI mode if CS is low.)
(http://www.retroleum.co.uk/mmc_cards.html )
In idle state, the card accepts only CMD0, CMD1, ACMD41 and CMD58. Any other commands will be
rejected. In this time, read OCR with CMD58, check working voltage range indicated by the OCR. In case
of the system supply voltage is out of working voltage range, the card must be rejected. Note that all
cards work at voltage range of 2.7 to 3.6 volts at least.
(http://users.ece.utexas.edu/~valvano/EE345M/view12_SPI_SDC.pdf )

TERCER PASO:
SEND COMMAND CMD1 REPEATEDLY UNTIL THE ``IN IDLE STATE`` BIT IN R1 RESPONSE IS SET TO
‘’0’’ AND THERE ARE NO ERROR BITS SET.
(http://m.eet.com/media/1114317/1515_ch3.pdf )
La tarjeta se mantiene bloqueada hasta que mandamos el comando CMD1 o el ACMD41 que
inicia un proceso de reset. Repetimos hasta desbloquear la tarjeta.
(https://deinventos.com/utilizar-una-sd-como-unidad-de-almacenamiento-para-pic-
programacion-basica/ )

Repeatedly send CMD1 (41h,00h,00h,00h,00h,00h) and check the response.. 


When response is 00h, the card is ready (this can take hundreds of milliseconds)
(http://www.retroleum.co.uk/mmc_cards.html )

Para inicializar la memoria se debe mandar por el microcontrolador el comando CMD1 con el
pin C2 a 0 V la estructura del comando tiene la siguiente forma: (0x41, 0x00, 0x00, 0x00, 0x00,
0xFF), una vez recibido los datos la memoria responde acertadamente con 0x00.
(https://drive.google.com/file/d/1IhBYfNMBtBTLjNc88J8VenbFwM8hc61xpnuec9-CrflFK-
id0VzbthIljGb3/view?pref=2&pli=1 )

La tarjeta se inicia el proceso de inicialización cuando un CMD1 se recibe. Para


detectar final del proceso de inicialización, el controlador de host debe enviar
CMD1 y comprobar la respuesta hasta el final de la inicialización. Cuando la tarjeta
se inicializa con exito, En estado de reposo poco en la respuesta R1 se borra (R1
resp cambia 0x01 a 0x00). (When the card is initialized successfuly, In Idle State bit in the
R1 response is cleared (R1 resp changes 0x01 to 0x00)). El proceso de inicialización puede
tomar cientos de milisegundos (tarjetas grandes tienden a más largo), de modo que
esta es una consideración a determin el tiempo de espera de valor. Después se aclaró
bit en estado de reposo en, lectura genérica / escritura serán capaces de ser
aceptados comandos.

‘’Because ACMD41 instead of CMD1 is recommended for SDC, trying ACMD41 first and
retry with CMD1 if rejected, is ideal to support both type of the cards.’’

The MultiMediaCard requires a defined reset sequence. After power on reset or CMD0 (software reset)
the card enters an idle state. Note that a t least 74 clock cycles are required prior to starting bus
communication. At this state the only legal host command is CMD1 (SEND_OP_COND). In SPI mode,
however, CMD1 has no operands.

The host must poll the card (by repeatedly sending CMD1) until the ‘in-idle-state’ bit in the card response
indicates (by being set to 0) that the card completed its initialization processes and is ready for the next
command.

(https://drive.google.com/file/d/18aOvwJU2gEFrk_iYfxMV4QhHId1V5YzGIICh_7jFjtM7COgXRkhn4
QC1yJEO/view?pref=2&pli=1 )
( http://elm-chan.org/docs/mmc/mmc_e.html )
Estado de reposo (idle state) o busy == (0x01)

First, I’m not using ACMD41 which is for SD cards and allows sending over some extra
parameters.  I’m using the good old CMD1 which is for MMC cards, because I don’t need any
parameters; and it works well for SD cards also.

(http://patrickleyman.be/blog/sd-card-c-driver-init/ )

6. Initialization Complete

Once all the above commands have sent, the clock speed can be cranked up to any speed your
card can support.  I’m using 12MHz (Fosc/4)

(http://patrickleyman.be/blog/sd-card-c-driver-init/ )

------LUEGO DE INICIADA, AHORA VAMOS A ESCRIBIR Y LEER EN ELLA---------

Para configurar el bloque de escritura y lectura (CMD16) el microcontrolador debe enviar los
argumentos del comando (6 Bytes) indicando en los 4 bytes adicionales (2-5 Bytes) el tamaño
del bloque, para las pruebas se configuro el bloque a 512 Bytes, entonces, la cadena a enviar
por el microcontrolador es (0x50, 0x00, 0x00, 0x02, 0x00, 0xFF), una vez recibido los datos la
memoria responde afirmativamente con un 0x00 como se ilustra en la figura 4.

(https://drive.google.com/file/d/1IhBYfNMBtBTLjNc88J8VenbFwM8hc61xpnuec9-CrflFK-
id0VzbthIljGb3/view?pref=2&pli=1 )

The initial block length can be set larger than 512 on 2GB card, so that the block size should be
reinitialized with CMD16 if needed.
(http://users.ece.utexas.edu/~valvano/EE345M/view12_SPI_SDC.pdf )
Set Block Length

The last step is to set the block length or sector size if you want to 512 bytes with CMD10
(SET_BLOCKLEN).  To do so, I send over 0x50, 0x00, 0x00, 0x02, 0x00, 0xff and I expect
0x00 from the first attempt:

Once all the above commands have sent, the clock speed can be cranked up to any speed your
card can support. I’m using 12MHz (Fosc/4)

(http://patrickleyman.be/blog/sd-card-c-driver-init/ )
Por último definimos la longitud del bloque que se va a leer y escribir con el CMD16.
Como tenemos memoria suficiente usaremos 512 bytes que es el bloque por defecto, pero si
queremos podemos configurar este valor incluso a 1 byte.
(https://blog.deinventos.com/utilizar-una-sd-como-unidad-de-almacenamiento-para-pic-
programacion-basica/ )

The initial read/write block length can be set 1024 on 2GB cards, so that the block size should
be re-initialized to 512 with CMD16 to work with FAT file system.
(http://elm-chan.org/docs/mmc/mmc_e.html )

Trás la inicialización podemos usar el comando SET_BLOCKLEN (CMD16) para fijar el tamaño del
bloque de datos (que se pasa como argumento). El tamaño "nativo" de las tarjetas SD es
de 512 bytes. En operaciones de lectura se puede especificar un tamaño de bloque entre
1 y 512 bytes. Las operaciones de escritura deben hacerse en bloques de 512. Lo normal
es usar el BLOCKLEN nativo de 512.
Una vez inicializada la tarjeta, volvemos a poner la máxima velocidad posible (Fosc/4) en el
reloj del módulo SPI (si es que empezamos con una velocidad lenta) para agilizar las
transferencias de información.
(http://picfernalia.blogspot.com/2013/04/interfaz-con-tarjetas-sd-protocolo-spi.html )
htt

p://elm-chan.org/docs/mmc/mmc_e.html
(http://elm-chan.org/docs/mmc/mmc_e.html )
La lectura y la escritura corresponden a los comandos CMD17 y CMD24 con un entero de 32bits
como parametro indicando la posición en bytes dentro de la memoria. Después de recibir la
respuesta al comando, o bien leemos o escribimos un byte (token) y luego los datos deseados
terminamos con el CRC de los datos que puede ser ignorado porque está desactivado por defecto.
(https://blog.deinventos.com/utilizar-una-sd-como-unidad-de-almacenamiento-para-pic-
programacion-basica/ )
Write/read : http://users.ece.utexas.edu/~valvano/EE345M/view12_SPI_SDC.pdf
http://picfernalia.blogspot.com/2013/04/tarjetas-sd-lecturaescritura-de-datos.html

https://blog.deinventos.com/utilizar-la-sd-como-unidad-de-almacenamiento-para-pic-sistema-de-
archivos-fat/
http://microembebidos.com/2013/05/07/tutorial-msp430-usci_b0-spi-sdmmc-parte-iii/

CMD17 (READ_SINGLE_BLOCK) starts a block read and after a complete transfer the card
goes back to Transfer State.
Block write (CMD24 - 27) means that one or more blocks of data are transferred from the host to
the card with a CRC appended to the end of each block by the host. If the CRC fails, the card
will indicate the failure on the DAT line (see below); the transferred data will be discarded and
not written and all further transmitted blocks (in multiple block write mode) will be ignored.

Single Block Read—The host selects one card for data read operation by CMD7, and sets the
valid block length for block oriented data transfer by CMD16. The basic bus timing for a read
operation is given in Figure 5-10. The sequence starts with a single block read command
(CMD17) which specifies the start address in the argument field. The response is sent on the
CMD line as usual.

Single Block Write—The host selects one card for a data write operation by CMD7. The host
sets the valid block length for block oriented data transfer (a stream write mode is also available)
by CMD16. The basic bus timing for a write operation is given in Figure 5-13. The sequence
starts with a single block write command (CMD24) which determines (in the argument field) the
start address. It is responded by the card on the CMD line as usual.

Data Read SPI mode supports single block read operation only (MultiMediaCard CMD17).
Upon reception of a valid read command the card will respond with a response token followed
by a data token in the length defined in a previous SET_BLOCK_LENGTH (CMD16) command

Data Write As for the read operation, while in SPI mode the MultiMediaCard supports single
block write only. Upon reception of a valid write command (MultiMediaCard CMD24) the card
will respond with a response token and will wait for a data block to be sent from the host. CRC
suffix and start address restrictions are identical to the read operation (refer to Figure 6-3). The
only valid block length, however, is 512 bytes. Setting a smaller block length will cause a write
error on the next write command.

After a data block is received the card will respond with a data-response token and if the data
block is received with no errors it will be programmed. As long as the card is busy programming,
a continuous stream of busy tokens will be sent to the host (effectively holding thedataOut line
low).

Once the programming operation is completed, the host must check the results of the
programming using the SEND_STATUS command (CMD13). Some errors (e.g. address out of
range, write protect violation, etc.) are detected during programming only. The only validation
check performed on the data block and communicated to the host via the data-response token is
CRC.
(https://drive.google.com/file/d/18aOvwJU2gEFrk_iYfxMV4QhHId1V5YzGIICh_7jFjtM7COg
XRkhn4QC1yJEO/view?pref=2&pli=1 )

It took 535 us to read one block (logic analyzer resolution too slow for SCLK)
The argument specifies the location to start to read in unit of byte or block. The sector
address specified by upper layer must be scaled properly. When a CMD17 is accepted, a
read operation is initiated and the read data block will be sent to the host. After a valid
data token is detected, the host controller receives following data field and two byte CRC.
The CRC bytes must be flushed even if it is not needed. If any error occurred during the
read operation, an error token will be returned instead of data packet.
(http://users.ece.utexas.edu/~valvano/EE345M/view12_SPI_SDC.pdf )

//////_________////////

Incluso en tarjetas SDSC donde se permiten accesos a bytes individuales haremos bien en usar un buffer
lo más grande posible en el PIC e ir llenándolo con los datos. Cuando el buffer esté lleno se arrancará el
proceso de volcado a la tarjeta y se volvera a reusar el buffer para los nuevos datos. Igualmente en las
operaciones de lectura leeremos un bloque de datos lo más grande posible y luego iremos "leyendo" los
bytes individuales en el PIC.

En cuanto al tamaño del buffer idealmente debería de ser de 512 bytes, el tamaño de un sector típico de
las tarjetas SD. Sólo si tenemos problemas de memoria en nuestro dispositivo podríamos hacerlo más
pequeño, pero tratando de no bajar de 256 o 128 bytes.

Si se va a usar un buffer de menos de 512 bytes es preciso avisar a la tarjeta del nuevo tamaño de bloque
a usar con el comando CMD_SET_BLOCKLEN (que usamos en la inicialización para fijar el bloque a 512
bytes).
(http://picfernalia.blogspot.com/2013/04/tarjetas-sd-lecturaescritura-de-datos.html )

Informacion complementaria: Antes de enviar el comando se verifica que la línea esta libre (alta). Se
detecta al recibir 0xFF.
Se manda el COMANDO + 4 bytes de argumento + CRC.
El CRC enviado solo es correcto para dos comandos CMD00 y CMD08 que se mandan al principio. En
todos los demás casos se usa un CRC=0xFF.
Se espera hasta recibir una respuesta tipo R1, con el primer bit igual a 0. LLegamos a esperar hasta 10
peticiones de respuesta antes de desistir.

También podría gustarte