SD Cards and FAT32 - Part 1


Working on my Alius 6502 computer I have gathered a significant amount of wisdom around working with SD Cards and FAT32. I am documenting all this as much for myself as others.

Bottom up thinking

Over sevral posts we will look at the whole SD Card and FAT32 system from the bottom up:

  • Electrical Interface
  • SPI Connections
  • SPI Modes
  • An SD Card in SPI mode
  • Reading Sectors
  • The boot sector
  • The partition table
  • Searching the Directoy
  • Directory entries

Electrical Interface

An SD Card and a MicroSD Card have the exact same electrical interface, just diffrent pin size.

An SD Card runs at 3.3V and depending on your computer you might have a 5V system. If you have a 5V system then you will need a logic level shifter like a 74HC4050. Another option might be to just get a MicroSD breakout board from Adafruit as they have a 5V safe board.

SPI Connections

The biggest problem with SPI is that it’s not really an offical standard.

The typical SPI bus needs 4 wires, 2 for data, one for clock and one for chip select. The issue is that the names for the lines can be one of many ‘standards’

In most documentation you will see once device called ‘Master’ and the other as ‘Slave’. You will also see it documented as ‘Controler’ and ‘Peripheral’

The data from the Controler to the Peripheral can be marked as any one of:

  • MOSI
  • SIMO
  • SDI

The data from the Peripheral to the Controler can be marked as any one of:

  • MISO
  • SOMI
  • SDO

NOTE: You will need a pull up resistor on the MISO line. I use a 1k resistor.

The clock line is mark as any of:

  • CLK
  • SCK
  • SCLK
  • SCL
  • CLOCK

The Chip Select can be marked as any one of:

  • SS
  • CS
  • CSN
  • CE

NOTE: The Chip Select line is active low, often written with a bar over the name.

SPI Modes

The next problem is with the clock phase and when data is latched by the SPI device.
Mode 0 the clock is idle low, and the data is latch on the rising edge of the clock.
Mode 1 the clock is idle low, and the data is latch on the falling edge of the clock.
Mode 3 the clock is idle high, and the data is latch on the falling edge of the clock.
Mode 4 the clock is idle high, and the data is latch on the rising edge of the clock.

An SD Card runs in Mode 0.

For Mode 0 we leave the Clock low, set the data bit, cycle the clock high and then low again.

What’s next?

In part 2 we will get the SD Card into SPI mode.