Outlining SD SPI with DMA design
The plan defines a full SD card SPI init state machine (CMD0 to ACMD41), CRC7 command validation, and DMA-based block read/write using STM32 HAL, including timing and response checks; next I'll implement core functions like CRC7, send command, init sequence, and read/write blocks with DMA.
/* sd_spi.c - Minimal SD‑card over SPI driver using DMA
*
* Targets any STM32 device with HAL SPI + DMA support.
* Wire SD: CS to a GPIO, SCK/MISO/MOSI to an SPI port.
*/
#include "stm32fxxx_hal.h"
#include <string.h>
#include <stdbool.h>
extern SPI_HandleTypeDef hspi1; /* configured for Mode0, 400kHz during init */
#define hspi (&hspi1)
#define SD_CS_PORT GPIOA
#define SD_CS_PIN GPIO_PIN_4
#define SD_CS_LOW() HAL_GPIO_WritePin(SD_CS_PORT, SD_CS_PIN, GPIO_PIN_RESET)
#define SD_CS_HIGH() HAL_GPIO_WritePin(SD_CS_PORT, SD_CS_PIN, GPIO_PIN_SET)
/* SD commands in SPI mode */
#define CMD0 0
#define CMD8 8
#define CMD16 16
#define CMD17 17
#define CMD24 24
#define CMD55 55
#define CMD58 58
#define ACMD41 41
/* Tokens */
#define DATA_TOKEN 0xFE
#define STOP_TOKEN 0xFD
/* Internal flags */
static bool sd_high_capacity = false;
/* --- Low-level helpers --------------------------------------------------- */
/* Send a single byte over SPI and receive back one byte */
static uint8_t spi_txrx(uint8_t tx)
{
uint8_t rx;
HAL_SPI_TransmitReceive(hspi, &tx, &rx, 1, HAL_MAX_DELAY);
return rx;
}
/* Pulse 8 clocks with MOSI high (0xFF) */
static void spi_clock_dummy(void)
{
uint8_t dummy = 0xFF, rx;
HAL_SPI_TransmitReceive(hspi, &dummy, &rx, 1, HAL_MAX_DELAY);
}
/* Compute CRC7 as per SD specification; polynomial x^7 + x^3 + 1 (0x89) */
static uint8_t crc7(const uint8_t *data, int len)
{
uint8_t crc = 0;
for (int i = 0; i < len; ++i) {
uint8_t d = data[i];
for (int b = 0; b < 8; b++) {
crc <<= 1;
if (d & 0x80)
crc |= 1;
d <<= 1;
if (crc & 0x80)
crc ^= 0x12; /* 0x89 << 1 is 0x112; we keep 8 bits */
}
}
return (crc >> 1) & 0x7F;
}
/* Send an SD command with CRC7, return first R1 byte */
static uint8_t sd_send_cmd(uint8_t cmd, uint32_t arg)
{
uint8_t frame[6];
frame[0] = 0x40 | cmd;
frame[1] = (uint8_t)(arg >> 24);
frame[2] = (uint8_t)(arg >> 16);
frame[3] = (uint8_t)(arg >> 8);
frame[4] = (uint8_t)(arg);
frame[5] = (crc7(frame, 5) << 1) | 1; /* CRC7 + end bit */
SD_CS_LOW();
/* Send 6‑byte frame */
for (int i = 0; i < 6; i++)
spi_txrx(frame[i]);
/* Read response: R1 is sent within 8 bytes */
uint8_t r1 = 0xFF;
for (int i = 0; i < 8; i++) {
r1 = spi_txrx(0xFF);
if ((r1 & 0x80) == 0)
break;
}
return r1;
}
/* --- Initialization state machine --------------------------------------- */
HAL_StatusTypeDef SD_Init(void)
{
uint8_t r1;
uint32_t t0;
SD_CS_HIGH();
/* At least 74 clocks with CS high */
for (int i = 0; i < 10; i++) spi_clock_dummy();
/* CMD0: reset to idle */
r1 = sd_send_cmd(CMD0, 0);
SD_CS_HIGH();
spi_txrx(0xFF);
if (r1 != 0x01) return HAL_ERROR;
/* CMD8: check voltage range */
r1 = sd_send_cmd(CMD8, 0x1AA);
uint8_t cmd8_resp[4] = {0};
if (r1 == 0x01) {
/* Read rest of R7 */
for (int i = 0; i < 4; i++) cmd8_resp[i] = spi_txrx(0xFF);
}
SD_CS_HIGH();
spi_txrx(0xFF);
bool sd_v2 = false;
if (r1 == 0x01 && cmd8_resp[2] == 0x01 && cmd8_resp[3] == 0xAA) {
sd_v2 = true;
}
/* ACMD41 loop */
uint32_t arg = sd_v2 ? 0x40000000 : 0x00000000;
t0 = HAL_GetTick();
do {
r1 = sd_send_cmd(CMD55, 0);
SD_CS_HIGH();
spi_txrx(0xFF);
if (r1 > 0x01) return HAL_ERROR;
r1 = sd_send_cmd(ACMD41, arg);
SD_CS_HIGH();
spi_txrx(0xFF);
if (r1 == 0x00) break;
} while ((HAL_GetTick() - t0) < 1000); /* 1 second timeout */
if (r1 != 0x00) return HAL_TIMEOUT;
/* CMD58: read OCR to check CCS */
r1 = sd_send_cmd(CMD58, 0);
if (r1 != 0x00) {
SD_CS_HIGH(); spi_txrx(0xFF);
return HAL_ERROR;
}
uint8_t ocr[4];
for (int i = 0; i < 4; i++) ocr[i] = spi_txrx(0xFF);
SD_CS_HIGH(); spi_txrx(0xFF);
if (sd_v2 && (ocr[0] & 0x40)) sd_high_capacity = true;
/* If SDSC (byte addressing), set block length to 512 */
if (!sd_high_capacity) {
r1 = sd_send_cmd(CMD16, 512);
SD_CS_HIGH(); spi_txrx(0xFF);
if (r1 != 0x00) return HAL_ERROR;
}
/* Optionally, switch SPI to higher speed (e.g. 12MHz) here */
return HAL_OK;
}
/* --- DMA block read/write ------------------------------------------------ */
/* Utility to wait for a data token from the card */
static HAL_StatusTypeDef wait_for_token(uint8_t token, uint32_t timeout_ms)
{
uint32_t t0 = HAL_GetTick();
uint8_t b;
do {
b = spi_txrx(0xFF);
if (b == token) return HAL_OK;
} while ((HAL_GetTick() - t0) < timeout_ms);
return HAL_TIMEOUT;
}
/* Callback flags for DMA completion */
static volatile bool dma_done = false;
void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *h) { dma_done = true; }
/* Read a single 512‑byte block using DMA */
HAL_StatusTypeDef SD_ReadBlockDMA(uint32_t lba, uint8_t *buf)
{
uint8_t r1;
uint32_t addr = sd_high_capacity ? lba : lba * 512;
r1 = sd_send_cmd(CMD17, addr);
if (r1 != 0x00) {
SD_CS_HIGH(); spi_txrx(0xFF);
return HAL_ERROR;
}
/* Wait for data token 0xFE */
if (wait_for_token(DATA_TOKEN, 100) != HAL_OK) {
SD_CS_HIGH(); spi_txrx(0xFF);
return HAL_TIMEOUT;
}
/* Receive 512 data bytes + 2 CRC bytes via DMA */
uint8_t dummy_tx[514];
memset(dummy_tx, 0xFF, sizeof(dummy_tx));
dma_done = false;
HAL_SPI_TransmitReceive_DMA(hspi, dummy_tx, buf, 512);
while (!dma_done) { /* spin */ }
uint8_t crc_in[2];
crc_in[0] = spi_txrx(0xFF);
crc_in[1] = spi_txrx(0xFF);
/* CRC16 check omitted here; can be implemented if required */
SD_CS_HIGH(); spi_txrx(0xFF);
return HAL_OK;
}
/* Write a single 512‑byte block using DMA */
HAL_StatusTypeDef SD_WriteBlockDMA(uint32_t lba, const uint8_t *buf)
{
uint8_t r1;
uint32_t addr = sd_high_capacity ? lba : lba * 512;
r1 = sd_send_cmd(CMD24, addr);
if (r1 != 0x00) {
SD_CS_HIGH(); spi_txrx(0xFF);
return HAL_ERROR;
}
/* Send a single‑block start token */
spi_txrx(DATA_TOKEN);
/* Transmit data + 2 dummy CRC bytes via DMA */
dma_done = false;
HAL_SPI_Transmit_DMA(hspi, (uint8_t *)buf, 512);
while (!dma_done) { /* spin */ }
spi_txrx(0xFF); /* CRC bytes can be dummy in SPI mode */
spi_txrx(0xFF);
/* Check data response token */
uint8_t resp = spi_txrx(0xFF);
if ((resp & 0x1F) != 0x05) {
SD_CS_HIGH(); spi_txrx(0xFF);
return HAL_ERROR;
}
/* Wait for card to finish programming (line goes high) */
while (spi_txrx(0xFF) == 0x00) { /* busy */ }
SD_CS_HIGH(); spi_txrx(0xFF);
return HAL_OK;
}
Usage notes:
- Configure your SPI handle
hspi1 at a slow rate (~400 kHz) for SD_Init(), then switch to a higher baudrate after initialization.
- Ensure
SD_CS_PIN is configured as GPIO output and pulled high by default.
- The
crc7() helper calculates the 7‑bit CRC required for command packets (CRC is actually only checked by the card on CMD0/CMD8 in SPI mode, but this code computes it for all commands).
- DMA callbacks must be installed to set
dma_done when a transfer completes. For production code, replace the busy‑wait loops with proper RTOS semaphores or events.
- The initialization state machine follows the sequence CMD0 → CMD8 → (CMD55+ACMD41 loop) → CMD58 → CMD16 (if needed) as defined in the SD SPI spec, with timeouts for ACMD41.
This forms a minimal driver for single‑block DMA read/write operations over SPI with proper command CRC7 and initialization timing.