Vous êtes sur la page 1sur 7

3/9/13

Share 4

Nerd Club: How SPI works with an SD card

More

Next Blog

hotkillers94@gmail.com

Dashboard

Sign Out

Home
FRIDAY, 2 NOVEMBER 2012

Blog

Videos
BLOG ARCHIVE

Shop

How SPI works with an SD card


SD cards have two main operating modes. Their default mode is high-speed through 4-bit wide port but we're going to be working with the "legacy" SPI (two-wire) mode. In SPI mode, the master device (our microcontroller) talks to the slave device (the sd card) using a data and a clock line. Every time the clock line goes from low-tohigh (or, if you prefer, from high-to-low - you can change this to suit the application needs) the receiving device looks at the data line. If it's high, it receives the single-bit value 1, if it's low, zero.

2013 (20) 2012 (136) December (12) November (13) Large format vinyl cutter at BuildBrighton Foison ... DipTrace for home etching, gerber export, 3d views... Etching heater DipTrace and the amazing 3D render DC blocking capacitor Different speakers sound different FAT/FAT16 tables - finding the data Another video interruption serial audio with a P...

in this example, when the clock line goes from low-to-high (sometimes called a rising edge trigger) as denoted by the red vertical lines in the clock timing diagram, the state of the data line is converted into a value The great thing about SPI is that it's not time dependent. Because the master device sends the clock line along with the data, it can be speeded up and slowed down (this is not possible using methods such as UART/serial, which has a fixed data rate; ie. the data has to be moved within a specific time period). Using this clock-and-data method, we can send commands to the sd card, to tell it to do specific things. So we can send a specific value (the sd format sets out specific values to send for specific commands) to get it to reset, for example. When an SD card has received and understood a command, it can remain in a busy state for quite some time. It is important to wait until the card has finished doing whatever you asked it to do, before blasting more data or commands at it. To do this, we poll the card (continuously ask it for data) until it gives us a "ready" token. SPI is actually a data exchange mechanism. There's no difference between reading and writing bytes between the devices. As one device sends a byte of data, so the other transmits one. After sending a single byte of data from an SPI
nerdclub-uk.blogspot.in/2012/11/how-spi-works-with-sd-card.html

Understanding FAT tables Reading and writing to a single sector on an SD ca... How SPI works with an SD card Talking to an SD card from a PIC 16F1825 microcont... A short interruption for a demo October (12) September (17) August (19) July (11) June (17) May (4) April (12) March (3) February (12) January (4)
1/7

3/9/13

Nerd Club: How SPI works with an SD card

buffer another (possibly different) byte may appear in it's place - this is the byte that has been received. So to read a byte from the sd card, we have to send it a byte too. It's normal to send either all zeros (0x00) or all ones (0xFF in hex is 255 in decimal, which is 11111111 in binary) for "don't care" bytes - so if you're just reading data from the other device, and it's not important what data you send, it's common to either send 0x00 or 0xFF. Whenever a command is sent to an SD card, it follows a specific format: There is a single command byte There are four "parameter" bytes - data which tells the recipient how to perform the command requested There is a single CRC (checksum) byte to prove that the previous bytes have been transmitted correctly. To send data to our SD card, we need a couple of functions:

2011 (153)

ABOUT ME

Chris Holden Computer nerd. Software AND hardware development - web apps, microchips, electronics, PCB design and manufacture, USB device RnD. View my complete profile
FOLLOW BY EMAIL Email address... Submit

SUBSCRIBE TO
U I n t 8s d S p i B y t e ( U I n t 8d a t a ) { s s p 1 b u f=d a t a ; w h i l e ( ! ( s s p 1 s t a t&( 1 < < B F ) ) ) ; r e t u r ns s p 1 b u f ; }

Posts Comments

SHARE IT
s t a t i ci n l i n ev o i d s d S e n d C o m m a n d ( U I n t 8c m d ,U I n t 3 2p a r a m ) { U I n t 8s e n d [ 6 ] ; s e n d [ 0 ]=c m d|0 x 4 0 ; s e n d [ 1 ]=p a r a m> >2 4 ; s e n d [ 2 ]=p a r a m> >1 6 ; s e n d [ 3 ]=p a r a m> >8 ; s e n d [ 4 ]=p a r a m ; s e n d [ 5 ]=( s d C r c 7 ( s e n d ,5 ,0 )< <1 )|1 ; f o r ( c m d=0 ;c m d<s i z e o f ( s e n d ) ;c m d + + ) { s d S p i B y t e ( s e n d [ c m d ] ) ; } }

Share this on Facebook Tweet this


View stats
(NEW) Appointment gadget >>

LABELS

16F1825 (6) 16f877a (5) 18f2455 (10) 18F4550 (17) 3d (1) android (1) arduino (3) arm7 (1) AT45DB041D (3) audio (9) basic4android (1) bass (5) belt and pulley (3) berlin (2) bill of materials (1) binary (3) bipolar (3) blood bowl (10) board game (6) bom (1)
2/7

This provides us with a simple method of sending commands (and their parameters) to the SD card. The first function simply puts a value into the hardware SPI buffer then waits for the SPI busy register value to go "not-busy" before returning the value it finds in the buffer (which is now the value received from the other device - data exchange remember!) The second function actually sends commands to the sd card. Every command byte sent to an SD must have bit 6 set (so the device can recognise it as a command and not some data). Bit 6 in binary is 01000000 which is 64 in decimal or 0x40 in hex. So to make sure that every command byte has bit 6 set, we always OR the command byte with 0x40 (so when we send command zero, for example, it's actually transmitted as 0x40, command one is sent as 0x41 and so on). But every time we send a command (and it's parameters), we have to wait for a not-busy response from the SD card. While the SD card is busy, it holds its
nerdclub-uk.blogspot.in/2012/11/how-spi-works-with-sd-card.html

3/9/13

Nerd Club: How SPI works with an SD card

"output pin" high - the data clocked out of it is always 11111111 (or 0xFF) So we build these little functions:

brighton (1) brighton fringe festival (2) buildbrighton (29) calibration (1) character lcd (4) charlie-plexing (5) christmas (1) chuck (5) clocks (1) cnc (38) controller (1) customstuff (2) darlington transistor (3) delta robot (2) deskjam (1) diptrace (5) drilling (26) eagle (1) element14 (1) embedded (1) enclosure (1) etching (5) expresspcb (6) farnell (8) fat tables (2) ferric chloride (1) flash eeprom (2) ftdi (2) fuzzface (6) g-code (4) google+ (1) guitar pedal (10) guitar wiring (1) hackspaces (1) hardware (4) haxe (3) hitatchi 44780 (4) hpc (1) http client (2) inkscape (1) invisible instrument (11) irf640 (1) kits (1) l293d (1) laser cutter (16) lathe (5)

s t a t i ci n l i n eU I n t 8 s d R e a d R e s p ( v o i d ) { U I n t 8v ,i=0 ; d o { v=s d S p i B y t e ( 0 x F F ) ; } w h i l e ( i + +<1 2 8& &( v= =0 x F F ) ) ; r e t u r nv ; } s t a t i cU I n t 8s d C o m m a n d A n d R e s p o n s e ( U I n t 8c m d ,U I n t 3 2p a r a m ) { U I n t 8r e t ; s d S p i B y t e ( 0 x F F ) ; s d S e n d C o m m a n d ( c m d ,p a r a m ) ; r e t=s d R e a d R e s p ( ) ; r e t u r nr e t ; }

This sdCommandAndResponse function sends a "dummy byte" to the sd card. It then sends the command byte, followed by the 4-byte parameter value(s). Next it calls the read-response function, which continuously sends the dummy byte 0xFF to the sd card, until the response back is not busy. When the response goes not busy, the response value is returned to the sdCommandAndResponse function. The response could either be "all ok" or it may be some kind of error code to explain why the command given could not be completed. One last function to mention is the CRC generating function. Strictly speaking, once we've told our card to work in SPI legacy mode, we don't actually need to generate the CRC values, but it's included here for completeness. Note: We didn't actually create this function, we ported it from another sd card library for another platform :
s t a t i cU I n t 8s d C r c 7 ( U I n t 8 *c h r , U I n t 8c n t , U I n t 8c r c ) { U I n t 8i ,a ; U I n t 8D a t a ; f o r ( a=0 ;a<c n t ;a + + ) { D a t a=c h r [ a ] ; f o r ( i=0 ;i<8 ;i + + ) { c r c< < =1 ; i f (( D a t a&0 x 8 0 )^( c r c&0 x 8 0 )){ c r c^ =0 x 0 9 ; } D a t a< < =1 ; } } r e t u r nc r c&0 x 7 F ; }

Before we can actually start sending data over SPI, we need to set up the PIC to use the hardware SPI peripheral. This means writing some values to particular registers in the chip. The names of these registers should be similar across different PIC models, but may not be exactly the same if you're using a different chip:

s t a t i cv o i ds d S p i I n i t ( v o i d ) { s s p 1 a d d =2 1 ; s s p 1 c o n 1 =0 b 0 0 1 0 1 0 1 0 ; s s p 1 s t a t =0 b 1 1 0 0 0 0 0 0 ;

/ / s l o wc l o c kd o w nt o<4 0 0 k h z / / s p im a s t e r ,c l k = t i m e r 2 / / C P H A=0

ldr (5) llangollen (4)


3/7

nerdclub-uk.blogspot.in/2012/11/how-spi-works-with-sd-card.html

3/9/13
}

Nerd Club: How SPI works with an SD card

logic analyser (5) longworth (2) ls3020 (3) makerfaire (3) mbed (4) microband (11) midi (11) milling (2) miniature drumkit (2) miniature drums (1) miniature guitar (19) miniature synth (4) multi-plexing (7) nerd club (3) new website (2) npn (1) oomlout (3) oshonsoft (3) pcb (31) pcbcart (3) petanque (2) pic (13) pickit2 (1) pinhole lens (1) pnp (1) poker (11) press-n-peel (1) programmer (4) quick-teck (2) resistors (3)

The important registers here are the SSP1ADD (multiplier value) ad SSP1CON1 register. When the last four bits of SSP1CON1 are 1010 this slows down the SPI clock speed - by how much depends on the value in the SSP1ADD register (and the actual speed, as in time taken to send each clock pulse, is dependent on the overall processor clock speed so will change with each chip model). When the last four bits are set to 0000, the SPI clock changes on every instruction cycle. When it's set to 1010, it changes on every x clock cycles, where x is the value held in the SSP1ADD register. The SD card initialisation routine after powering up is: Set the clock speed to less than 400khz Hold the chip select line on the card low and send in about 80 clock pulses Pull the chip select line high to tell the card we're talking to it Send in the "soft reset" command (CMD0) Wait for the sd card to respond "ok" with the value 0x01 Send in the "initialise card" command (CMD1) Repeat sending CMD1 until the card responds with an ok value of 0x00 Set the sector size using CMD16 with a parameter 512 (each sector is 512 bytes) Turn of the CRC requirement by sending CMD59 (all future transmissions do not require a valid crc value) The next time the card responds with an "ok" value, it has been initialised and we can ramp the clock up to full speed.

All of the initialisation routines have to be carried out at the relatively slow clock speed of not more than 400khz. So we need a couple of extra functions to enable us to set the clock speed and enable the chip select line:

rfid (2) rgb (4) robotics (2) router (1) salvaging (3) saxophone (3) scalectrix (1) schematic (1) sd card (10) serial (4) servos (11) shadow harp (6) shift register (4) simplified (1) sms-to-web (2) smt (7) smt-to-dip (4) soldering (4)
4/7

s t a t i cv o i ds d C l o c k S p e e d ( B o o l e a nf a s t ) { i f ( f a s t ) { s s p 1 c o n 1=0 b 1 1 1 1 0 0 0 0 } e l s e { s s p 1 c o n 1=0 b 1 1 1 1 1 0 1 0 } } v o i ds d C h i p S e l e c t ( b o o la c t i v e ) { p o r t c . 3=! a c t i v e ; }

For debugging, we've written a simple "fatal error" function to let us know which part of the initialisation failed (if there are any problems). When a fatal error is hit, this function reports it, then puts the microcontroller into "sleep mode" so that the program flow is permanently interrupted.
nerdclub-uk.blogspot.in/2012/11/how-spi-works-with-sd-card.html

3/9/13
v o i df a t a l ( U I n t 8v a l ) { U I n t 8i ,j ,k ;

Nerd Club: How SPI works with an SD card


/ / f a t a le r r o r :f l a s hL E Dt h e ng ot os l e e p

sourceboost (2) stepper motor (17) teardown (1) touch-sensor (2) traffic lights (2) twitter (1) uart (2) uln2803a (1) unipolar (3) usart (2) usb (15) video (2) vinculum (1) voltage divider (2) wah (5) word clock (7) xaml (3)

f o r ( j=0 ;j<5 ;j + + ) { f o r ( k=0 ;k<v a l ;k + + ) { d e l a y _ m s ( 1 0 0 ) ; P _ L E D=1 ; d e l a y _ m s ( 1 0 0 ) ; P _ L E D=0 ; } U A R T L o g ( " E r r o r " , v a l ) ; d e l a y _ m s ( 2 5 0 ) ; d e l a y _ m s ( 2 5 0 ) ; } w h i l e ( 1 ) { a s ms l e e p } }

By using all these functions together, we can now write our sdInit routine:

zif (1)

B o o l e a ns d I n i t ( ) { U I n t 8v ,t r i e s=0 ; B o o l e a nS D ; S D=f a l s e ; s d S p i I n i t ( ) ;/ /i n i t i a l i s eS P I s d C l o c k S p e e d ( f a l s e ) ;/ /s l o wc l o c k s d C h i p S e l e c t ( f a l s e ) ;/ /C Si n a c t i v e f o r ( v=0 ;v<2 0 ;v + + ){ s d S p i B y t e ( 0 x F F ) ; / / l o t so fc l o c k st og i v ec a r dt i m et oi n i t } s d C h i p S e l e c t ( t r u e ) ;/ /C Sa c t i v e v=s d C o m m a n d A n d R e s p o n s e ( 0 ,0 ,t r u e ) ; i f ( v! =1 ) { f a t a l ( 2 ) ; } v=s d C o m m a n d A n d R e s p o n s e ( 1 ,0 ,t r u e ) ; f o r ( i n ti = 0 ; v! =0& &i < 5 0 ; + + i ) { d e l a y _ m s ( 5 0 ) ; v=s d C o m m a n d A n d R e s p o n s e ( 1 ,0 ,t r u e ) ; } i f ( v ) { f a t a l ( 3 ) ; } v=s d C o m m a n d A n d R e s p o n s e ( 1 6 ,5 1 2 ,t r u e ) ; i f ( v ) { f a t a l ( 5 ) ; } v=s d C o m m a n d A n d R e s p o n s e ( 5 9 ,0 ,t r u e ) ; i f ( v ) { f a t a l ( 6 ) ; } / /n o ws e tt h es dc a r du pf o rf u l ls p e e d s d C l o c k S p e e d ( t r u e ) ; r e t u r nt r u e ; } / / s e cs e c t o rs i z e / / c r co f f

If this function successfully returns true, the SD card has been successfully initialised and the SPI lines set to run at maximum speed for the fastest (spibased) data transfer.
Posted by Chris Holden at 10:21
nerdclub-uk.blogspot.in/2012/11/how-spi-works-with-sd-card.html 5/7

3/9/13
+4 Recommend this on Google

Nerd Club: How SPI works with an SD card

Labels: sd card

No comments: Post a Comment


E n t e ry o u rc o m m e n t . . .

Comment as: JAY (Google) Publish Preview

Sign out Subscribe by email

Newer Post
Subscribe to: Post Comments (Atom)

Home

Older Post

SEARCH THIS BLOG Search

POPULAR POSTS

Press-n-peel alternative Press and peel is that great blue powdery paper used for printing circuits onto, to transfer onto copper clad board (either with a domestic ... Playing audio with a PIC 16F1825 microcontroller and SD card It's taken literally weeks to get right, but finally, we've got a working example of how to play a raw/wav file from an SD card usin... How to drive a stepper motor with a PIC microcontroller We've made a few posts about this before, while investigating how stepper motors work, but with our recent CNC drilling machine competit... Inkjet printer teardown - get at those stepper motors! At last night's BuildBrighton open evening, we set to work opening up an old HP Inkjet printer, using our favourite opening-tools - hamm... Stepper motor control 2-phase 4-phase Critical to getting our CNC-based pick-andplace machine working is driving the stepper motors. We've already managed to get some 4-ph...

nerdclub-uk.blogspot.in/2012/11/how-spi-works-with-sd-card.html

6/7

3/9/13

Nerd Club: How SPI works with an SD card

Picture Window template. Powered by Blogger.

nerdclub-uk.blogspot.in/2012/11/how-spi-works-with-sd-card.html

7/7

Vous aimerez peut-être aussi