The NandTier SeriesPart 8 of 12

SD Cards over SPI

A byte-at-a-time SPI engine in hardware, and the C that wakes an SD card up, asks it questions and reads 512-byte blocks.

11 min readSD cardSPIPeripherals
In this article
  1. What are we trying to do?
  2. The SPI engine
  3. One byte, from C
  4. Commands
  5. Waking the card up
  6. Reading a block
  7. Trying it
  8. Conclusion

What are we trying to do?

The flash holds the launcher, but the games, and anything else we want to change without rebuilding firmware, should live on a microSD card. The Tang Nano 9K has a slot wired to four FPGA pins.

SD cards speak a complex native protocol, but every card also supports a simpler SPI mode: the same four wires as the flash (select, clock, data in, data out), with commands and answers as bytes. So the plan is:

Splitting it that way keeps the hardware tiny and puts the complicated, changeable part where it is easy to debug: in software, with the UART to print what happens.

The SPI engine

The peripheral has four registers:

hw/periph/nt_sd_spi.vlines 7–14
7// Registers:8//   +0x0 TX    write: start sending this byte (ignored while busy);9//              read: 010//   +0x4 RX    the byte received by the last transfer (read only)11//   +0x8 CTRL  bit 0 SCK, bit 1 MOSI, bit 2 CS: pin levels while no12//              transfer runs (read/write);13//              bit 3 MISO pin, bit 4 busy (read only)14//   +0xC DIV   SCK half period in clock cycles, 1..255 (reset: DEFAULT_DIV)

Write a byte to TX and the engine clocks it out while clocking a byte in, which appears in RX. CTRL lets software drive the pins directly when no transfer is running: chip select is controlled that way, and it can read the busy flag. DIV sets the clock speed.

The engine's state is a shift register, a bit count and a counter for half a clock period:

hw/periph/nt_sd_spi.vlines 41–47
41reg  [7:0] tx_shift, rx_byte;42reg  [3:0] bits_left;43reg  [7:0] phase_count;44reg        sck;45 46wire busy = bits_left != 4'd0;47wire wr   = valid && wstrb[0];

Starting a transfer loads the byte and the count:

hw/periph/nt_sd_spi.vlines 63–67
63if (wr && addr[3:2] == 2'd0 && !busy) begin64    tx_shift    <= wdata[7:0];65    bits_left   <= 4'd8;66    phase_count <= div;67    sck         <= 1'b0;

Then each half period toggles the clock. SPI mode 0 means: the card samples on the rising edge and changes its output on the falling edge, so we do the same:

hw/periph/nt_sd_spi.vlines 68–80
68end else if (busy) begin69    if (phase_count != 8'd1) begin70        phase_count <= phase_count - 8'd1;71    end else begin72        phase_count <= div;73        sck <= !sck;74        if (!sck) begin75            rx_byte <= {rx_byte[6:0], sd_miso};    // rising edge: sample76        end else begin77            tx_shift  <= {tx_shift[6:0], 1'b1};   // falling edge: next bit78            bits_left <= bits_left - 4'd1;79        end80    end

On the rising edge (!sck before the toggle) we sample miso into rx_byte. On the falling edge we shift the next bit out and count one bit fewer. After eight bits busy falls.

cssckmosib7b6b5b4b3b2b1b0misob7b6b5b4b3b2b1b0sample on the rising edge
One byte in SPI mode 0. Both sides change their data on the falling edge and sample it on the rising edge.

The pins are the engine's while it runs, and the manual values otherwise:

hw/periph/nt_sd_spi.vlines 85–87
85assign sd_sck  = busy ? sck : man_sck;86assign sd_mosi = busy ? tx_shift[7] : man_mosi;87assign sd_cs   = man_cs;
InteractiveThe real nt_sd_spi: select the card, write a byte to TX and watch it go out while the card's reply comes in.

One byte, from C

The C side starts with the smallest possible function: send a byte, wait, return what came back.

fw/common/sd.clines 13–19
13static uint8_t xfer(uint8_t out)14{15    SD_TX = out;16    while (SD_CTRL & SD_CTRL_BUSY)17        ;18    return SD_RX;19}

Everything else is built on xfer. Chip select is a write to CTRL, with MOSI held high (the idle level for SD):

fw/common/sd.clines 21–31
21static void select_card(int on)22{23    // MOSI idles high, SCK low24    SD_CTRL = SD_CTRL_MOSI | (on ? 0 : SD_CTRL_CS);25}26 27static void deselect(void)28{29    select_card(0);30    xfer(0xFF);         // the card releases MISO after one more byte31}

The extra xfer(0xFF) after deselecting is an SD quirk: the card only lets go of its data line after one more byte of clock.

Commands

Every SD command is six bytes: 0x40 | command number, a 32-bit argument, and a CRC. The card answers with a one-byte status called R1, but not immediately: it sends FF until it is ready, so we keep clocking until bit 7 is clear.

fw/common/sd.clines 40–58
40// Send a command, return the R1 answer (bit 7 set: no answer). The card41// stays selected.42static uint8_t command(uint8_t cmd, uint32_t arg, uint8_t crc)43{44    uint8_t r1 = 0xFF;45 46    select_card(1);47    for (int i = 0; i < 1000 && xfer(0xFF) != 0xFF; i++)48        ;49    xfer(0x40 | cmd);50    xfer(arg >> 24);51    xfer(arg >> 16);52    xfer(arg >> 8);53    xfer(arg);54    xfer(crc);55    for (int i = 0; i < 10 && (r1 & 0x80); i++)56        r1 = xfer(0xFF);57    return r1;58}

In SPI mode the card only checks the CRC on the first two commands, which is why most calls pass a dummy 0x01.

Waking the card up

A fresh card needs a ritual before it will read anything. Here it is, step by step:

power up80 clocks, CS highCMD0→ 01 idleCMD8→ 01 · 1AAACMD41→ 00 readyCMD16512-byte blocksfast clockready to readask again, up to 1 sslow: 400 kHz or less
The start-up ritual. Each step answers with a status byte; ACMD41 is repeated until the card is ready.
fw/common/sd.clines 65–69
65SD_DIV = DIV_INIT;66select_card(0);67wait_cycles(NT_CLK_HZ / 1000);          // 1 ms after power-up68for (int i = 0; i < 10; i++)            // at least 74 clocks with CS high69    xfer(0xFF);

Power up. Slow clock, card deselected, wait a millisecond, then at least 74 clock pulses with chip select high. Ten bytes of FF is 80.

fw/common/sd.clines 71–75
71r1 = command(0, 0, 0x95);72if (r1 != 0x01) {73    status = 0x10 | (r1 & 0x0F);74    goto done;75}

CMD0, GO_IDLE_STATE. Reset the card into SPI mode. It answers 01: "idle". This is one of the two commands where the CRC must be right: 95.

fw/common/sd.clines 77–89
77r1 = command(8, 0x1AA, 0x87);78if (r1 != 0x01) {79    status = 0x20 | (r1 & 0x0F);80    goto done;81}82xfer(0xFF);83xfer(0xFF);84r7[0] = xfer(0xFF);85r7[1] = xfer(0xFF);86if (r7[0] != 0x01 || r7[1] != 0xAA) {87    status = 0x30;88    goto done;89}

CMD8, SEND_IF_COND. "Can you work at 3.3 V?" with the check pattern AA. A modern (SDHC/SDXC) card echoes the voltage and the pattern back. An old card would answer "illegal command" here.

fw/common/sd.clines 91–106
91// ACMD41 with HCS until the card leaves the idle state (up to ~1 s)92status = 0x05;93for (int i = 0; i < 1000; i++) {94    r1 = command(55, 0, 0x01);95    if (r1 > 0x01) {96        status = 0x40 | (r1 & 0x0F);97        break;98    }99    r1 = command(41, 0x40000000, 0x01);100    if (r1 == 0x00) {101        status = 0;102        break;103    }104    deselect();105    wait_cycles(NT_CLK_HZ / 1000);106}

ACMD41, start initialisation. An "application command" is CMD55 followed by the command. Argument bit 30 (HCS) says we support high-capacity cards. The card answers 01 while it is still busy starting up and 00 when it is ready, which can take up to a second, so we ask up to a thousand times, a millisecond apart.

fw/common/sd.clines 110–118
110    r1 = command(16, SD_BLOCK_SIZE, 0x01);111    if (r1 != 0x00)112        status = 0x60 | (r1 & 0x0F);113 114done:115    deselect();116    if (status == 0)117        SD_DIV = DIV_FAST;118    return status;

CMD16 sets the block size to 512 bytes, and with that the card is ready: the clock goes up to full speed (DIV_FAST).

Each failure returns a status code whose high nibble says which step failed, so a terminal message like "SD init failed, status 0x2x" points straight at CMD8.

Reading a block

With the card ready, reading 512 bytes is CMD17 with the block number, then wait for the data token FE, then the data:

fw/common/sd.clines 121–142
121int sd_read_block(uint32_t block, uint8_t *buf)122{123    int ok = 0;124 125    if (command(17, block, 0x01) == 0x00) {126        for (uint32_t i = 0; i < 100000; i++) {127            uint8_t token = xfer(0xFF);128            if (token == 0xFE) {129                for (int j = 0; j < SD_BLOCK_SIZE; j++)130                    buf[j] = xfer(0xFF);131                xfer(0xFF);         // CRC, ignored132                xfer(0xFF);133                ok = 1;134                break;135            }136            if (token != 0xFF)      // error token137                break;138        }139    }140    deselect();141    return ok ? 0 : -1;142}

The card can take a while to fetch the block, so we wait up to 100,000 bytes for the token. Anything other than FF or FE is an error token. The two CRC bytes after the data are read and ignored.

Trying it

The launcher has commands to test the card. With a card in the slot:

Serial terminal
> TSD card initialised.> RSD block 1024: ...

T runs sd_init, R reads a test block and prints its first bytes, W writes a pattern to a block, reads it back and compares.

Conclusion

A byte engine of about 50 lines of Verilog and 150 lines of C are all it takes to read an SD card. The card does the heavy lifting (it has its own controller inside), and SPI mode lets us talk to it one byte at a time.

We now have storage for games. Before we can show one, we need a picture: in the next article we generate HDMI from scratch.