Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
216 changes: 216 additions & 0 deletions libraries/SDIO/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
# STM32 SDIO / SDMMC

Raw sector access for STM32F1, F2, F4, F7 and H5 devices that actually have
SDIO or SDMMC. F0/F3 devices without those peripherals cannot use this driver.
The library selects SDIO, SDMMC1 or SDMMC2 from the chosen pins or from
`setInstance()`. SDMMC1 and SDMMC2 have independent ownership and IRQ routing.
It does not implement a filesystem or SPI mode.

Use `#include <SDIO.h>` and the global **`SDCard`** object. `SDIO` remains
the CMSIS hardware macro and cannot also name a C++ object on F1/F2/F4.
`begin()` returns a success flag; `getError()` returns the active SD or MMC
HAL error code. `getHandle()` exposes the SD handle; `getMMCHandle()` exposes
the separate MMC handle when HAL MMC is enabled.

The public object is `SDCard`. Card-detection callback registration uses
`setDetectionCallback(callback)`. No object or callback aliases are provided.
The sector units of `read()`/`write()` are unchanged.

Core 2.9 and the repository's 3.x core are supported by the same sources.
The EXTI bridge selects the 2.9 port/HAL-pin-mask registration API or the
3.x `PinName` API at compile time. Callback detachment remains in C++ for
correct linkage on both cores; disabled EXTI builds remain supported.

## Configurable data clock and diagnostic history

Call `setClock(hz)` before `begin()` or `beginMMC()`. It accepts a requested
maximum between 1 Hz and 52 MHz, rejecting zero, higher rates, and changes
while initialized without changing the previous setting. In 1-bit mode,
requests above 25 MHz are rejected. `begin()` also validates width and
medium: SD 4-bit requests are limited to 50 MHz; MMC/eMMC 4/8-bit requests
are limited to 52 MHz. Changing the width after `setClock()` cannot bypass
these checks. The peripheral's
divider range imposes a family/clock-dependent minimum: `begin()` returns
false if it cannot represent the requested speed. `getClock()` returns the
requested limit; `getActualClock()` returns the clock read back from the
controller's divider after successful initialization, or zero before
initialization and after `end()`. Dividers round up, so the actual clock
does not exceed the requested limit (e.g. 15 MHz gives 12 MHz from 48 MHz).
The setting persists across `end()`. The default remains 25 MHz.

Identification and width negotiation always run at a safe clock. Before
raising the data clock above 25 MHz, SD cards must confirm CMD6 High Speed;
MMC/eMMC must advertise a suitable SDR speed in EXT_CSD DEVICE_TYPE and
accept HS_TIMING=1. The legacy HALs use the LL CMD6/status path; H5 SD uses
the HAL speed-negotiation API. Unsupported or failed switching makes
initialization fail without enabling the faster clock. `entry.high_speed`
records successful negotiation. The configured clock remains bounded by
both the requested limit and the controller: legacy SDIO/SDMMC uses divider
bypass only up to 48 MHz, so a 50/52 MHz request often yields 48 MHz. If a
divider can only yield a rate <=25 MHz, no High Speed switch is needed.
This implementation covers 3.3 V SDR High Speed, not UHS, DDR, HS200 or HS400.
For SD speed modes, see the
[SD Association specification](https://www.sdcard.org/cms/wp-content/themes/sdcard-org/dl.php?f=Part1_Physical_Layer_Simplified_Specification_Ver7.10.pdf).

Diagnostic logging is disabled by default. Enable it before initialization:

```cpp
alignas(32) static uint8_t sector[512];
SDCard.setClock(15000000U);
SDCard.setLogging();
if (SDCard.begin(true) && SDCard.read(sector, 0, 1)) {
SDCard.wait(1000);
}
sd_log_entry_t entry;
for (uint32_t i = 0; i < SDCard.getLogCount(); ++i) {
if (SDCard.getLog(i, entry)) {
// inspect entry.operation, phase, status, error, command and response[]
}
}
SDCard.end();
```

Each instance retains its own last 10 entries in a fixed ring without heap
allocation. `getLog(0, entry)` copies the oldest retained entry; out-of-range
indices return false. `clearLog()` clears the history, and `setLogging(false)`
stops new entries while retaining existing ones. The history survives `end()`
and reinitialization.

Entries describe initialization, read/write/erase submissions and failures,
observed transfer completion, aborts and shutdown. They include millisecond
timestamps, controller, sector/count, SD/MMC, DMA, width, requested/actual
clock, HAL error bits, and snapshots of CMD/ARG/RESP1-4. `registers_valid`
is false if the object does not own a live controller (e.g. pin validation
failed). This is an operation diagnostic log, not a trace of every low-level
HAL command. Completion is recorded when `wait()`/`isBusy()` observes the
result, or before a subsequent valid transfer; no log work is added to IRQ
handlers. A pending operation stopped by `end()` is recorded as cancelled
(`SD_ERROR`). Read the log from the foreground, like the other public APIs.

`SDIO_LOG_CAPACITY` is a build-wide definition controlling the ring size.
Set it to 0 to remove log storage and recording, keeping the API available
with zero entries. Increasing it increases RAM per `SDIOClass` object.

## SD and MMC/eMMC

| Medium | Width | Initialization |
| --- | --- | --- |
| SD card | 1 or 4 bits | `setDataMode(SDIO_MODE_1B/4B)`, then `begin(useDMA)` |
| MMC/eMMC | 1, 4 or 8 bits | select width, then `beginMMC(useDMA)` |
| MMC/eMMC | 8 bits | `setDataMode(SDIO_MODE_8B)`, then `begin(useDMA)` also selects MMC |

Eight-bit mode uses **HAL MMC**, including its card identification, bus-width
negotiation, capacity, transfers, errors and IRQ handler. It is not an attempt
to put a normal SD card into 8-bit mode. This is SDR sector access, not an
HS200/HS400, RPMB or boot-partition API.

Enable the HAL modules for the **whole build**, for example in the sketch's
`build_opt.h`:

```text
-DHAL_SD_MODULE_ENABLED=
-DHAL_MMC_MODULE_ENABLED=
-DHAL_UART_MODULE_ENABLED=
```

UART is only needed for example diagnostics. External DMA also requires
HAL DMA, normally enabled by the core. MMC is optional: without its HAL
module, SD still compiles and requesting MMC/8-bit initialization returns
false with `HAL_SD_ERROR_UNSUPPORTED_FEATURE`.

## Pins and controller selection

Configure pins and width before initialization. Common SDIO/SDMMC1 wiring
on the requested MCU families is:

| Signal | Pin |
| --- | --- |
| D0-D3 | PC8, PC9, PC10, PC11 |
| CK, CMD | PC12, PD2 |
| D4-D7 for MMC 8-bit | PB8, PB9, PC6, PC7 |

Check the selected **package**, variant pin map and board wiring. Pins left
as `NC` default to entries for the same controller. Mixed-controller pins
or missing signals are rejected. H562 LQFP64 does not expose PB9/D5 and
therefore supports this wiring only in 1/4-bit mode; VFQFPN68 and larger
applicable packages expose D5. See the ST
[H562/H563 pin table](https://www.st.com/resource/en/datasheet/stm32h562vg.pdf).

For the second controller on a device that has it, use a separate object:

```cpp
SDIOClass second;
second.setInstance(SDMMC2); // guarded by #if defined(SDMMC2) in portable code
second.setDataMode(SDIO_MODE_8B);
bool ready = second.beginMMC(true); // defaults to this variant's SDMMC2 pins
```

Pin setters `setD0()` through `setD7()`, `setCMD()` and `setSCK()` accept
Arduino pin numbers or `PinName` values. Use the latter for explicit alternate
pin mappings, such as `PB_8_ALT1`. When reusing an object for a different
controller, reset its old pins to `NC` or supply all new pins. One object may
own each controller at a time. Objects cannot be copied or moved. Do not call
the API concurrently or from an ISR. Board-specific transceiver routing can
be implemented through the weak `SDIO_MspInit/DeInit` hooks; the default
H5 configuration uses direct 3.3 V signaling without a transceiver.

## Clocks and DMA

The library reads the selected kernel clock and calculates the data divider;
it does not reconfigure the board's PLLs. F1 uses HCLK; the F1 SD/MMC HAL
identification dividers in this core are corrected for HCLK up to 72 MHz.
F2/F4/F7 use their PLLQ/CLK48 and SDMMC muxes, not PCLK2. Their legacy HAL
uses a fixed identification divider, so a selected input above 48 MHz is
rejected rather than exceeding the initial 400 kHz card clock. H5 queries
RCC for the selected SDMMC instance and uses its `clock / (2 * divider)`
formula, with the HAL handling the identification divider. Normal requested
data speed defaults to 25 MHz and can be increased after High Speed negotiation.

The generic H562 variant has an empty `SystemClock_Config()`. The examples
explicitly call `SDIOExampleConfigureClock()` to supply SDMMC1 from a 48 MHz
PLL2R/CSI source if the kernel clock is stopped. This optional helper assumes
PLL2 is available. Applications sharing PLL2 should configure the clock at
board level instead.

| Family / controller | DMA engine and reserved IRQs |
| --- | --- |
| F1 SDIO | DMA2 Channel4 (RX/TX); Channel4 or shared Channel4/5 vector |
| F2/F4 SDIO | DMA2 Stream3 RX, Stream6 TX, channel4; SDIO IRQ |
| F7 SDMMC1 | DMA2 Stream3 RX, Stream6 TX, channel4; SDMMC1 IRQ |
| F7 SDMMC2 | DMA2 Stream0 RX, Stream5 TX, channel11; SDMMC2 IRQ |
| H5 SDMMC1/2 | SDMMC internal DMA (IDMA); only that SDMMC IRQ, no GPDMA allocation |

Do not allocate the reserved streams/channels/vectors to another peripheral.
On high-density F103, the shared Channel4/5 vector is reserved as a whole.
`SDIO_IRQ_PRIORITY` defaults to 5 and is configurable for the whole build.

Buffers must be word aligned, or **32-byte aligned on F7**, where the driver
cleans TX cache lines and cleans/invalidates RX lines before DMA, then
invalidates RX again on completion, error or abort. Full-sector sizes cover
whole cache lines. Buffers must be in DMA-accessible memory; F4 CCM is
rejected. Keep DMA buffers alive and untouched until `wait()` succeeds or
`isBusy()` becomes false and `getError()` has been checked.

External DMA permits 1-511 sectors per call. H5 IDMA and polling permit
1-65535 sectors. The caller supplies `blocks * 512` bytes and splits larger
requests. Addresses are logical 512-byte sectors, including on SDSC cards.
Erase endpoints are inclusive; check the medium's erase granularity.

Polling read/write wait for card readiness. DMA read/write return after
starting the transfer. Always wait before accessing its buffer:

```cpp
alignas(32) static uint8_t sector[512];
if (SDCard.begin(true) && SDCard.read(sector, 0, 1) && SDCard.wait(1000)) {
// sector can now be used
}
SDCard.end();
```

`wait(timeout)` checks HAL, DMA and card programming status, aborts DMA on
timeout, and returns false on error. Failed starts also stop DMA before
returning. `end()` stops transfers, disables owned IRQs and releases SDIO/
SDMMC pins and clocks, leaving the shared DMA2 clock enabled. Optional card
detection uses `setDetectionInput(arduinoPin, LOW/HIGH)` and
`setDetectionCallback(callback)`. Callbacks run in interrupt context and are detached by
`end()`. Without a detect pin, initialization still probes the medium.
Loading
Loading