Simvik

Receive a UART stream with circular DMA

Copy out the bytes DMA has written since the last poll, using its remaining-count register. A medium embedded C problem (DMA), run and graded in the browser.

medium · DMA · dma · uart · ring-buffer

A common way to receive UART data without an interrupt per byte: a DMA channel in circular mode writes every received byte into buf, wrapping back to the start at the end. The firmware polls now and then (from a timer, or the UART's idle-line interrupt) and takes out the new bytes.

The DMA controller does not tell you where it is directly. Its counter ndtr holds how many transfers are left before it wraps, counting down from RX_SIZE, so the next write position is RX_SIZE - ndtr (and ndtr == RX_SIZE means position 0).

Write dma_rx_poll(rx, ndtr, out): copy every byte written since rx->last, up to the current position, into out in order, handling the wrap, update rx->last, and return the number of bytes copied.

Starter code

int dma_rx_poll(rx_t *rx, uint16_t ndtr, uint8_t *out) {
  uint16_t pos = RX_SIZE - ndtr;
  int n = 0;
  for (uint16_t i = rx->last; i < pos; i++) out[n++] = rx->buf[i];
  rx->last = pos;
  return n;
}

Example tests

One message

rx_t rx = {0};
uint16_t ndtr = RX_SIZE;
dma_receive(&rx, &ndtr, "HELLO");
poll(&rx, ndtr);
poll(&rx, ndtr);

Expected output:

5: "HELLO"
0: ""

A message across the wrap

rx_t rx = {0};
uint16_t ndtr = RX_SIZE;
dma_receive(&rx, &ndtr, "HELLO");
poll(&rx, ndtr);
dma_receive(&rx, &ndtr, "ABCD");
poll(&rx, ndtr);

Expected output:

5: "HELLO"
4: "ABCD"

Learn it first

  • DMA · Transfer modes, circular buffers, half-transfer interrupts and cache coherency.

More DMA problems