skip to content

An embedded Rust flash driver on `embedded_hal::spi::SpiDevice` calls `write(&[0x9F])` then `read(&mut id)` and gets a wrong ID; why, and what fixes it?

level: seniorimportance: should knowfreq 19%

answer

  1. what chip-select does between calls
  2. every method is a transaction
  3. lock, assert, transfer, flush, deassert
  4. an Operation list in one call
  5. bus ownership versus device ownership

basics

~20 s

Each SpiDevice method is a complete transaction: it asserts chip-select, transfers, flushes and deasserts. The command and the read run under two separate selects, so the chip drops the command. Put both in one transaction with Operation::Write and Operation::Read.

solid answer

~50 s

`SpiDevice` represents one chip on a possibly shared bus, selected by its CS pin. Its `transaction(&mut [Operation])` locks the bus, asserts CS, runs every operation, flushes, deasserts CS and unlocks; `write`, `read` and `transfer` are shorthands for a one-operation transaction. So `write(&[0x9F])` followed by `read(&mut id)` releases CS between the command and the reply, and a command-response chip typically abandons a command when it is deselected. The fix is `self.spi.transaction(&mut [Operation::Write(&[0x9F]), Operation::Read(&mut id)])`. The trait choice matters too: a driver for a chip with a CS pin takes `SpiDevice` and never toggles CS itself, so other drivers can share the bus, while `SpiBus` means exclusive ownership of SCK, MOSI and MISO for chips without CS or bitbanged protocols. HALs must implement `SpiBus`; a `SpiDevice` usually comes from `embedded-hal-bus`, which pairs a bus with a CS pin.

code

rust · 31 lines
rust
#![no_std]

use embedded_hal::spi::{Operation, SpiDevice};

const READ_ID: u8 = 0x9F;

pub struct Flash<SPI> {
    spi: SPI,
}

impl<SPI: SpiDevice> Flash<SPI> {
    pub fn new(spi: SPI) -> Self {
        Self { spi }
    }

    /// One transaction: CS stays asserted from the command to the last ID byte.
    pub fn read_id(&mut self) -> Result<[u8; 3], SPI::Error> {
        let mut id = [0u8; 3];
        self.spi
            .transaction(&mut [Operation::Write(&[READ_ID]), Operation::Read(&mut id)])?;
        Ok(id)
    }

    /// Bug: two calls are two transactions, so CS goes high after the command.
    pub fn read_id_split(&mut self) -> Result<[u8; 3], SPI::Error> {
        let mut id = [0u8; 3];
        self.spi.write(&[READ_ID])?;
        self.spi.read(&mut id)?;
        Ok(id)
    }
}

go deeper

for a junior

Recall that SPI selects each chip with its own CS line and that embedded-hal 1.0 has separate SpiBus and SpiDevice traits.

for a middle

Explain that every SpiDevice method is a full transaction, so a command and its reply must go into one transaction call.

for a senior

Diagnose the split-transaction bug, choose SpiDevice over SpiBus plus a manual CS pin, and explain flush and early-returning SpiBus writes.

for a principal

Expect drivers for chips on a shared bus to take SpiDevice, so boards can add chips without driver changes and bus sharing stays in the application.

## Two traits for one set of wires An SPI bus shares its clock (SCK), MOSI and MISO lines between several chips, and each chip gets its own **chip-select (CS)** line, usually active-low. While its CS is high a chip ignores the bus and does not drive MISO; pulling CS low starts a conversation, and for command-based chips such as flash memories, displays and radios, releasing it ends the command. `embedded-hal` 1.0 models this with two traits in `embedded_hal::spi`: | Trait | Represents | Who implements it | A driver takes it when | |---|---|---|---| | `SpiBus` | exclusive ownership of SCK, MOSI and MISO | every HAL (required) | the chip has no CS, or SPI generates another protocol's waveform | | `SpiDevice` | one chip: its CS pin plus access to a possibly shared bus | `embedded-hal-bus`, and HALs with hardware CS | the chip has a CS pin | ## What a transaction does `SpiDevice::transaction(&mut [Operation])` is the core method. Its documentation lists the steps: 1. lock the bus, 2. assert CS, 3. perform all the operations, 4. flush the bus, 5. deassert CS, 6. unlock the bus. `Operation` has the variants `Read`, `Write`, `Transfer`, `TransferInPlace` and `DelayNs`. The convenience methods `read`, `write`, `transfer` and `transfer_in_place` are each defined as a transaction with a **single** operation: `write(buf)` is literally `self.transaction(&mut [Operation::Write(buf)])`. The locking mechanism is up to the implementation (a critical section, a blocking mutex, or returning an error or panicking when the bus is busy), but it must stop two transactions running on the same bus at once. ## The bug in the question `self.spi.write(&[0x9F])?; self.spi.read(&mut id)?;` is therefore two transactions. CS goes low, the command byte goes out, CS goes high, and the flash chip drops the command. The second transaction selects the chip again and clocks three bytes in, but the chip has no pending command to answer, so the bytes are whatever an undriven MISO line reads as. The fix keeps CS low across both parts: - `self.spi.transaction(&mut [Operation::Write(&[0x9F]), Operation::Read(&mut id)])`. - For a single full-duplex exchange, one `transfer` or `transfer_in_place` call is also one transaction. A host test with a fake `SpiDevice` that only answers a command written in the same transaction reproduces this: the single-transaction version returns the ID, the split version returns `[0xFF; 3]`. ## Why not take SpiBus and drive CS yourself A tempting fix is to bound the driver on `SpiBus` plus an `OutputPin` for CS and toggle the pin by hand. The `embedded_hal::spi` docs advise against it for chips that have a CS pin: - The driver then demands **exclusive** use of the bus, so the flash chip and, say, a display can no longer share it. - `SpiBus` methods may return **before** the bytes have left the hardware FIFO; raising CS without calling `flush()` first can cut off the last byte. `SpiDevice::transaction` flushes before deasserting CS. - CS-to-clock setup and hold delays belong in the configuration of the `SpiDevice`, and the docs say drivers should not use `Operation::DelayNs` for them. `SpiBus` is the right bound when the device has no CS pin, or when SPI is used to bitbang another protocol on MOSI, because sharing the bus makes no sense in either case. ## Catching it before the board does - Read every driver method that sends a command and then expects a reply: two consecutive `SpiDevice` calls are two chip-select cycles. - Give the host tests a fake `SpiDevice` that answers only inside the transaction that carried the command, as above; the split version then fails in `cargo test`. - On a bench, a logic analyser trace shows CS rising right after the command byte and falling again before the reply, which is the signature of this bug. ## Rules for HAL and application authors - HALs **must** implement `SpiBus` and must not add bus-sharing machinery at that level; they **may** also implement `SpiDevice` when the hardware manages CS. - The application builds a `SpiDevice` for each chip by combining the HAL's bus with that chip's CS pin, typically with the `embedded-hal-bus` crate, and passes it to the chip's driver. - Each driver then owns its `SpiDevice`, and the lock inside `transaction` keeps one driver's command from interleaving with another's.

  • With embedded-hal 1.0, when does a driver that owns a SpiBus have to call flush() itself?
    Before any GPIO change that must follow the last bit on the wire, such as raising a CS pin it manages or switching a display's data/command line, and before shutting the SPI peripheral down. `SpiBus` writes may return once data is in the FIFO, so `flush()` waits until the bus is idle. `SpiDevice::transaction` already flushes before it deasserts CS.
  • How do two Rust drivers share one SPI bus under embedded-hal 1.0?
    Each gets its own `SpiDevice`: the same bus behind some lock plus that chip's own CS pin, typically built with the `embedded-hal-bus` crate. `transaction` holds the lock for its whole duration, so one driver's command and reply cannot interleave with another driver's. Neither driver needs to know the other exists.

  • Each SpiDevice::write keeps CS asserted until the next read on the device.
  • A driver for a chip with CS should take SpiBus and toggle the CS pin itself.
  • HAL crates must implement SpiDevice, and SpiBus is optional for them.
  • When SpiBus::write returns, every byte has already gone out on the wire.
  • Operation::DelayNs is where a driver should encode the chip's CS setup time.