🚀 AI-Powered Mock Interviews Launching Soon - Join the Waitlist for Early Access

technicalmedium

You need to implement non‑blocking SPI communication with a sensor that requires a 10 µs turnaround between frames while the MCU runs a 2 kHz periodic sensor sampling task. How would you structure the code to meet timing constraints, avoid bus contention, and handle error conditions?

onsite · 3-5 minutes

How to structure your answer

Use a state‑machine + RTOS task + interrupt‑driven DMA. 1) Create a dedicated SPI task with high priority and a mailbox for frame requests. 2) Use DMA to transfer data, triggering an interrupt on completion. 3) In the ISR, schedule the next frame only after a 10 µs delay, using a hardware timer or RTOS delay. 4) Protect the SPI bus with a mutex to avoid contention with the 2 kHz sampling task. 5) Implement error handling by checking CRC or timeout flags in the ISR, then signal the task via a semaphore to retry or log the fault. 6) Ensure power‑saving by disabling the SPI peripheral when idle and re‑enabling only on request.

Sample answer

I would design a DMA‑driven SPI state machine that runs in a dedicated RTOS task with the highest priority. The task receives frame requests via a mailbox and initiates a DMA transfer. The DMA completion ISR checks for CRC or timeout errors; if an error occurs, it signals the task to retry or log the fault. To enforce the 10 µs turnaround, the ISR starts a hardware timer that, upon expiry, triggers the next frame. Bus contention is avoided by protecting the SPI bus with a mutex, ensuring the 2 kHz sampling task cannot preempt the SPI task. Power consumption is minimized by disabling the SPI peripheral when idle and re‑enabling only on request. This architecture guarantees timing, reliability, and efficient CPU usage.

Key points to mention

  • DMA transfer with ISR completion
  • 10 µs turnaround timer
  • Mutex for bus protection
  • Error detection via CRC/timeout

Common mistakes to avoid

  • Using blocking SPI calls that stall the 2 kHz task
  • Ignoring turnaround timing leading to frame loss
  • Neglecting error detection and retry logic