In this lesson, you will learn how to use interrupts and DMA to manage SPI data streams, ensuring your processor remains free to handle other tasks instead of waiting for serial transfers to finish.
The Problem with Polling in SPI
When using SPI for high-speed data acquisition, waiting for each byte to clock out (polling) forces the CPU to sit idle. Because SPI is full-duplex, every time you send a byte to a sensor, you receive one simultaneously. If your data rate is high, polling these flags will cause your main loop to stutter, missing critical events.
Interrupt-Driven Buffering
Instead of waiting for the SPI_TXE (Transmit Empty) or SPI_RXNE (Receive Not Empty) flags in a loop, we configure the SPI peripheral to trigger an Interrupt Service Routine (ISR).
When the SPI hardware finishes shifting 8 bits, it fires an interrupt. We use a circular buffer (learned in lesson 13) to store incoming bytes:
void SPI_IRQHandler(void) {
if (SPI_SR & RXNE_FLAG) {
// Immediately store incoming byte in circular buffer
buffer_push(spi_rx_buffer, SPI_DR);
}
if (buffer_is_not_empty(spi_tx_buffer)) {
// Load next byte to send
SPI_DR = buffer_pop(spi_tx_buffer);
}
}
DMA-Based Transfers
For even higher performance, we use Direct Memory Access (DMA). DMA acts as a bridge between the SPI data register and your system memory. You tell the DMA controller the address of your buffer and how many bytes to transfer, then "fire and forget." The DMA controller moves the data without any CPU intervention. Once the transfer is complete, the DMA triggers a single interrupt, notifying the CPU that the entire block is ready for processing.
This approach effectively decouples data movement from execution, allowing your CPU to perform complex calculations while the SPI peripheral independently handles the high-speed bit-banging required for full-duplex communication.
Key Takeaway: Interrupt-driven and DMA-based buffering decouple SPI data movement from the main execution flow, allowing high-speed full-duplex communication without stalling the processor.