SPI with external devices (sensors, displays) in Embedded C - Time & Space Complexity
When using SPI to talk with sensors or displays, it's important to know how long communication takes as data size grows.
We want to see how the time to send or receive data changes when we handle more bytes.
Analyze the time complexity of the following SPI data transfer code.
void spi_transfer(uint8_t* data, uint16_t length) {
for (uint16_t i = 0; i < length; i++) {
SPI_SendByte(data[i]);
while (!SPI_TransferComplete());
}
}
This code sends each byte one by one over SPI and waits for the transfer to finish before sending the next.
Look at what repeats in the code.
- Primary operation: Sending a byte over SPI and waiting for it to finish.
- How many times: This happens once for each byte in the data array, so exactly length times.
As you send more bytes, the total time grows in a straight line with the number of bytes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 byte sends and waits |
| 100 | 100 byte sends and waits |
| 1000 | 1000 byte sends and waits |
Pattern observation: Doubling the number of bytes doubles the total time needed.
Time Complexity: O(n)
This means the time to send data grows directly with the number of bytes you send.
[X] Wrong: "Sending more bytes over SPI takes the same time as sending just one byte."
[OK] Correct: Each byte requires its own send and wait, so more bytes mean more total time.
Understanding how SPI communication time grows helps you design efficient embedded systems and answer questions about data transfer speed.
"What if the SPI transfer was done using DMA (Direct Memory Access) instead of waiting for each byte? How would the time complexity change?"