Serial Peripheral Interface (SPI)
Overview
RTL8721F provides an SPI interface, a synchronous serial bus supporting master and slave roles with full-duplex transfer. The Rust driver ameba_hal::spi wraps the PAC register block directly — no raw bit-masking or C FFI is involved.
Features
Motorola SPI frame format via
FrameFormat::MotorolaSpi, with configurable data frame size from 4 to 16 bits viaFrameSizeMaster or Slave role via
Role::Master/Role::Slave, set withSpi::set_rolebeforeinitConfigurable clock phase and polarity via
ClkPhase/ClkPolarity, and transfer direction viaTransferMode::TransmitReceive/TransmitOnly/ReceiveOnlyConfigurable RX/TX FIFO threshold, DMA burst level, slave-select toggle behavior, and TX/RX byte or bit swap via
ConfigTwo peripheral instances,
Spi0andSpi1, both implementing the sharedSpiInstancetraitOperation mode:
Blocking: poll-driven
Async: interrupt-driven, via
embassywakerDMA-backed async: GDMA-driven transfer via
SpiDmaRaw ISR callback: user-registered handler via
Spi::register_irq, independent of the async/waker path
Note
Async slave mode is available through Spi::into_async_slave, returning a separate SpiSlaveAsync handle.
Operating Modes
SPI supports five operating modes: Blocking Mode, Async Mode, Async Slave Mode, DMA Mode, and Interrupt Mode.
Blocking Mode
The CPU polls the SPI status registers and pushes or pulls the FIFO buffer as needed. This is the default mode returned by Spi::steal(), and implements embedded_hal::spi::SpiBus. The role must be set with set_role before init, since the peripheral powers on as a slave.
use ameba_hal::spi::{Role, Spi, Spi0, SpiConfig};
use ameba_hal::{
pinmux::{self, Pin, PinFunction, Pull},
rcc,
};
...
rcc::enable(rcc::Peripheral::SPI0);
pinmux::set(Pin::PA7, PinFunction::SPI0);
pinmux::set(Pin::PA8, PinFunction::SPI0);
pinmux::set(Pin::PA9, PinFunction::SPI0);
pinmux::set(Pin::PA10, PinFunction::SPI0);
pinmux::set_pull(Pin::PA10, Pull::Up);
let spi = unsafe { Spi::<Spi0>::steal() };
// Set master role BEFORE init (default power-on is slave).
spi.set_role(Role::Master);
let cfg = SpiConfig::default();
spi.init(&cfg);
spi.set_slave_enable(0);
...
let tx: [u8; 16] = [
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10,
];
let mut rx = [0u8; 16];
// Write all bytes to TX FIFO (< 64 entries, no overflow risk).
for &b in tx.iter() {
spi.write_data(b as u32);
}
// Wait until TX FIFO drains and peripheral is idle.
while spi.is_busy() {}
Full example: examples/spi/blocking/src/main.rs.
Async Mode
Interrupt-driven master transfers built on the Embassy waker mechanism, obtained by calling into_async on an enabled blocking instance. Implements embedded_hal_async::spi::SpiBus, and also exposes write_async / read_async / transfer_async / transfer_in_place_async / flush_async directly.
use ameba_hal::spi::{InterruptHandler, Role, Spi, Spi0, SpiConfig};
use ameba_hal::{Async, Config};
use ameba_hal::{
pinmux::{self, Pin, PinFunction, Pull},
rcc,
};
...
ameba_hal::bind_interrupts!(struct Irqs {
SPI0_IRQ => InterruptHandler<Spi0>;
});
...
rcc::enable(rcc::Peripheral::SPI0);
pinmux::set(Pin::PA7, PinFunction::SPI0);
pinmux::set(Pin::PA8, PinFunction::SPI0);
pinmux::set(Pin::PA9, PinFunction::SPI0);
pinmux::set(Pin::PA10, PinFunction::SPI0);
pinmux::set_pull(Pin::PA10, Pull::Up);
let spi = unsafe { Spi::<Spi0>::steal() };
spi.set_role(Role::Master);
...
spi.init(&cfg);
spi.set_slave_enable(0);
...
let mut spi_async: Spi<Spi0, Async> = spi.into_async(Irqs);
...
let tx: [u8; 16] = [
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10,
];
let mut rx = [0u8; 16];
...
spi_async.transfer_async(&mut rx, &tx).await;
Full example: examples/spi/async/src/main.rs.
Async Slave Mode
Full-duplex slave transfer, obtained by calling into_async_slave on a blocking instance already configured with set_role(Role::Slave) and init. Returns a separate SpiSlaveAsync handle rather than going through SpiBus, since a slave never drives the clock and only exposes a single transfer_async method that completes once the master has clocked out the requested number of frames.
use ameba_hal::spi::{InterruptHandler, Role, Spi, Spi0, SpiConfig, SpiSlaveAsync};
use ameba_hal::{
pinmux::{self, Pin, PinFunction, Pull},
rcc,
};
...
ameba_hal::bind_interrupts!(struct Irqs {
SPI0_IRQ => InterruptHandler<Spi0>;
});
...
rcc::enable(rcc::Peripheral::SPI0);
pinmux::set(Pin::PA7, PinFunction::SPI0);
pinmux::set(Pin::PA8, PinFunction::SPI0);
pinmux::set(Pin::PA9, PinFunction::SPI0);
pinmux::set(Pin::PA10, PinFunction::SPI0);
pinmux::set_pull(Pin::PA10, Pull::Up);
let spi = unsafe { Spi::<Spi0>::steal() };
spi.set_role(Role::Slave);
let cfg = SpiConfig { role: Role::Slave, ..SpiConfig::default() };
spi.init(&cfg);
while spi.is_rx_not_empty() { let _ = spi.read_data(); }
let mut slave: SpiSlaveAsync<Spi0> = spi.into_async_slave(Irqs);
...
let mut tx = [0u8; LEN];
for (i, b) in tx.iter_mut().enumerate() {
*b = 0xA0u8 + i as u8; // [0xA0..0xAF]
}
let mut rx = [0u8; LEN];
// Preload `tx` onto MISO, wait for the master to clock LEN frames,
// receive the master's data into `rx`.
slave.transfer_async(&tx, &mut rx).await;
Full example: examples/board2board/spi-slave/src/main.rs (the actual slave-role counterpart, since examples/spi/ only covers loopback on a single board).
DMA Mode
GDMA-backed transfer, obtained by calling into_dma_async on an enabled blocking instance with a pair of DmaChannel handles for TX and RX. Suited for large buffers, since the CPU only sets up the transfer and awaits completion instead of touching the FIFO frame by frame.
use ameba_hal::dma::{Blocking, DmaChannel};
use ameba_hal::spi::{Role, Spi, Spi0, SpiConfig, SpiDma};
use ameba_hal::{
pinmux::{self, Pin, PinFunction, Pull},
rcc,
};
...
rcc::enable(rcc::Peripheral::SPI0);
pinmux::set(Pin::PA7, PinFunction::SPI0);
pinmux::set(Pin::PA8, PinFunction::SPI0);
pinmux::set(Pin::PA9, PinFunction::SPI0);
pinmux::set(Pin::PA10, PinFunction::SPI0);
pinmux::set_pull(Pin::PA10, Pull::Up);
let spi = unsafe { Spi::<Spi0>::steal() };
spi.set_role(Role::Master);
spi.init(&SpiConfig::default());
spi.set_slave_enable(0);
// into_dma_async takes ownership of both DMA channels, selects HS IDs, enables NVIC.
let mut spi_dma: SpiDma<Spi0, 0, 1> = spi.into_dma_async(
unsafe { DmaChannel::<0, Blocking>::steal() },
unsafe { DmaChannel::<1, Blocking>::steal() },
);
...
let tx_slice = unsafe { core::slice::from_raw_parts(tx_ptr as *const u8, BUF_SIZE) };
let rx_slice = unsafe { core::slice::from_raw_parts_mut(rx_ptr, BUF_SIZE) };
match embassy_time::with_timeout(
Duration::from_millis(500),
spi_dma.transfer_async(rx_slice, tx_slice),
).await {
Ok(()) => { ... }
Err(_) => { ... }
}
Full example: examples/spi/dma/src/main.rs.
Interrupt Mode
A user-registered raw ISR callback in master mode, obtained by calling register_irq on a blocking instance. The callback runs directly in the SPI’s NVIC interrupt context via the SpiIrqHandler trait, independent of the Embassy waker/executor path, useful when the main loop only writes and all receiving is handled from the ISR.
use core::ptr::addr_of_mut;
use core::sync::atomic::{AtomicU32, Ordering};
...
use ameba_hal::pinmux::{self, Pin, PinFunction, Pull};
use ameba_hal::println;
use ameba_hal::rcc;
use ameba_hal::spi::{
InterruptHandler, Role, Spi, Spi0, SpiConfig, SpiInstance, SpiIrqEvent, SpiIrqHandler,
read_available,
};
...
ameba_hal::bind_interrupts!(struct Irqs {
SPI0_IRQ => InterruptHandler<Spi0>;
});
struct RxCounter {
bytes: AtomicU32,
}
impl SpiIrqHandler for RxCounter {
fn on_irq(&mut self, event: SpiIrqEvent) {
if event.error {
println!("[SPI-IRQ] error isr=0x{:08X} (from ISR)", event.isr);
return;
}
let mut buf = [0u8; 16];
let n = unsafe { read_available(Spi0::PTR, &mut buf) };
self.bytes.fetch_add(n as u32, Ordering::Relaxed);
println!("[SPI-IRQ] rx {} byte(s): {:02X?} (from ISR)", n, &buf[..n]);
}
}
static mut RX_COUNTER: RxCounter = RxCounter { bytes: AtomicU32::new(0) };
...
rcc::enable(rcc::Peripheral::SPI0);
pinmux::set(Pin::PA7, PinFunction::SPI0);
pinmux::set(Pin::PA8, PinFunction::SPI0);
pinmux::set(Pin::PA9, PinFunction::SPI0);
pinmux::set(Pin::PA10, PinFunction::SPI0);
pinmux::set_pull(Pin::PA10, Pull::Up);
let spi = unsafe { Spi::<Spi0>::steal() };
// Set master role BEFORE init (default power-on is slave).
spi.set_role(Role::Master);
let cfg = SpiConfig::default();
spi.init(&cfg);
spi.set_slave_enable(0);
// Drain any stale RX FIFO data before registering the callback.
while spi.is_rx_not_empty() {
let _ = spi.read_data();
}
while spi.is_busy() {}
let handler = unsafe { &mut *addr_of_mut!(RX_COUNTER) };
spi.register_irq(handler, Irqs);
Full example: examples/spi/interrupt/src/main.rs.
Application Examples
The Rust SDK provides four example projects under examples/spi/:
-
Master mode, writes 16 bytes (0x01-0x10) to the TX FIFO and reads them back through the MOSI-MISO loopback for comparison.
Wiring: SPI0 — CLK=PA7, MOSI=PA8, MISO=PA9, CS=PA10. MOSI ↔ MISO jumper required.
[SPI BLK] start [PASS] SPI blocking: OK
-
Master mode at roughly 10 kHz, transfers 16 bytes while a heartbeat task runs every 5 ms, verifying the executor stays unblocked during the transfer and the looped-back data is correct.
Wiring: SPI0 — CLK=PA7, MOSI=PA8, MISO=PA9, CS=PA10. MOSI ↔ MISO jumper required.
[SPI async] start [HB] 1 [HB] 2 ... [SPI] heartbeats during transfer: N [PASS] SPI async: loopback + non-blocking OK [HB] N ...
The heartbeat task keeps printing
[HB] Nlines after the final[PASS]. -
Master mode, transfers 1024 looped-back bytes via GDMA channel 0 (TX) and channel 1 (RX), comparing data once the transfer completes.
Wiring: SPI0 — CLK=PA7, MOSI=PA8, MISO=PA9, CS=PA10. MOSI ↔ MISO jumper required.
[SPI DMA] start [SPI DMA] transfer done [PASS] SPI DMA: 1024 bytes loopback OK
-
The main loop blocking-sends 5 rounds of 4 bytes each, 50 ms apart, while a raw ISR callback registered via
register_irq/SpiIrqHandlerdrains and prints every received byte directly from interrupt context, independent of the waker/executor path used byspi/async.Wiring: SPI0 — CLK=PA7, MOSI=PA8, MISO=PA9, CS=PA10. MOSI ↔ MISO jumper required.
[SPI interrupt] start ... [SPI] [2] sent [42, 43, 44, 02] [SPI-IRQ] rx 3 byte(s): [42, 43, 44] (from ISR) [SPI-IRQ] rx 1 byte(s): [02] (from ISR) ... [PASS] SPI interrupt: 20 bytes echoed via ISR OK
The received bytes of one round may be split across several
[SPI-IRQ]lines, and an[SPI-IRQ]line can be printed before the matching[SPI] [n] sentline, so the order and split can differ from run to run.
Note
Build any example with cargo xtask build example --name spi/<demo>.
API Reference
Quick Usage
use ameba_hal::spi::{Role, Spi, Spi0, SpiConfig};
use embedded_hal::spi::SpiBus;
let spi = unsafe { Spi::<Spi0>::steal() };
spi.set_role(Role::Master);
spi.init(&SpiConfig::default());
spi.set_slave_enable(0);
let mut spi = spi;
let tx = [0x01u8, 0x02, 0x03, 0x04];
let mut rx = [0u8; 4];
let _ = spi.transfer(&mut rx, &tx);
Spi also implements embedded_hal_async::spi::SpiBus once converted with into_async, and exposes DMA-backed transfer via into_dma_async — see the Operating Modes section above.