I am using STM32F3 microcontrollers and the HAL library. For many peripherals (e.g. ADC, SPI, I2C), the HAL library provides 3 ways to read/write data: polling mode, interrupt mode, and DMA mode. I know I don't want the polling mode because it's blocking. However, I am unsure how to choose between interrupt and DMA mode. Is there a general rule of thumb? I feel like DMA mode should always be better because it can write values into memory without CPU intervention?
1 Answers
The advantage of DMA is that it does not require CPU intervention. DMA transfers can run while the CPU is busy doing other things, or while it is idle.
Some disadvantages of DMA are that:
Most microcontrollers have a limited number of DMA channels, so it may not be possible to use DMA for all peripherals.
The overhead of setting up and executing a DMA transfer may negate its benefits when many small transfers are required, e.g. when receiving individual characters over a USART.
Unusual interactions with devices (like bidirectional data transfers with some SPI devices) are often not supported with DMA.
DMA transfers place heavier (and less predictable) loads on the microcontroller's bus matrix, making them a frequent source of errata.
Generally speaking, I'd advise against using DMA for I2C. The protocol typically only runs at 100 - 200 kHz, so using interrupts will not place an especially heavy load on the microcontroller.