Simvik

Process ADC halves on time

Average the half of the buffer DMA has just finished, and count overruns. An easy embedded C problem (DMA), run and graded in the browser.

easy · DMA · dma · adc · double-buffer

An ADC streams into a buffer of 2 * HALF samples with circular DMA. The DMA raises half-transfer when the first half is full, and transfer-complete when the second half is full, then starts again. While the CPU processes one half, DMA fills the other: double buffering.

Write on_dma_event(s, ev):

  • for DMA_HALF, average the first half (buf[0] to buf[HALF - 1]); for DMA_COMPLETE, the second half; store the average (rounded down) in averages[count++],
  • events must alternate. If the same event arrives twice in a row, a half was missed (the CPU was too slow): add one to overruns, and still process the half.

Starter code

void on_dma_event(stream_t *s, dma_event_t ev) {
  uint32_t sum = 0;
  for (int i = 0; i < HALF; i++) sum += s->buf[i];
  s->averages[s->count++] = (uint16_t)(sum / HALF);
  (void)ev;
}

Example tests

Both halves

uint16_t buf[2 * HALF] = { 10, 20, 30, 40, 100, 200, 300, 400 };
stream_t s = { buf };
on_dma_event(&s, DMA_HALF);
on_dma_event(&s, DMA_COMPLETE);
show(&s);

Expected output:

averages: 25 250, overruns 0

Learn it first

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

More DMA problems