Electronic – Usage of callbacks and circular buffer UART reads using DMA

embeddedmicrocontrollerstm32

Trying to understand the flow of the DMA transfer via uart:

- Configure uart
- Configure dma
- enable DMA stream to initiate the transfer
- IRQ handler gets fired 
- disable interrupts, and invoke `DMAXferCmplCallback()` in case of receiving data from the uart
-  write the received data to a FIFO in memory (circular buffer) while keeping track of the start/end index.
-  process the data / do any action based on what was received?

Is that a general idea? My questions:

  • do we really need to have a callback? is the main reason for having it to mainly process the incoming data? is it better than something like:
    while(true) {
        usart_serial_read();
        parse_serial_read();
        execute_serial_data();
        //clear out the rx buffer for the next input ...
     }
  • is circular buffer really required if I don't have to keep track of past inputs? One reason I know circular buffers are useful is how you can continue writing to it without having to worry about overflowing it like in case of a linear buffer since you can wrap things around in a FIFO.
    How I have it now is I receive the data, store it into a linear buffer, parse it before \r, and then clear it. This way I have the full buffer prior to each input reading.
  • should the callback be a part of the uart or dma file?

Best Answer

In general, how to use DMA will depend on what data you transfer and how much.

At least I don't understand why would you disable interrupts, while on STM32 the DMA itself can implement a ring or ping-pong buffer. As soon as one half of the buffer is full, it triggers you with the interrupt (which calls the callback) and keeps receiving data into the second half of the buffer.

But if you are receiving say single keypresses from a terminal program, you most certainly don't want to wait until half-buffer worth of letters has arrived, you would poll the DMA controller if any bytes and how many bytes have been received so you can act on them.