SPI library usage in Arduino - Time & Space Complexity
When using the SPI library in Arduino, it's important to understand how the time to send data changes as you send more bytes.
We want to know how the program's running time grows when sending multiple bytes over SPI.
Analyze the time complexity of the following code snippet.
#include <SPI.h>
void setup() {
SPI.begin();
}
void loop() {
for (int i = 0; i < 100; i++) {
SPI.transfer(i);
}
delay(1000);
}
This code sends 100 bytes one by one over SPI repeatedly every second.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that calls
SPI.transfer()100 times. - How many times: 100 times per loop cycle, repeating every second.
As the number of bytes to send increases, the total time grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 SPI transfers |
| 100 | 100 SPI transfers |
| 1000 | 1000 SPI transfers |
Pattern observation: Doubling the number of bytes doubles the total SPI transfer calls and time.
Time Complexity: O(n)
This means the time to send data grows directly in proportion to the number of bytes sent.
[X] Wrong: "Sending more bytes over SPI takes the same time as sending just one byte."
[OK] Correct: Each byte requires a separate transfer call, so more bytes mean more time spent sending data.
Understanding how loops and hardware communication calls affect time helps you write efficient code and explain your reasoning clearly.
"What if we replaced the for-loop with a function that sends all bytes at once using a buffer? How would the time complexity change?"
