SPI with SD card module in Arduino - Time & Space Complexity
When using SPI to communicate with an SD card module, it's important to understand how the time taken grows as we read or write more data.
We want to know how the number of operations changes when the amount of data changes.
Analyze the time complexity of the following code snippet.
#include <SPI.h>
#include <SD.h>
File dataFile;
void setup() {
SD.begin(10); // Initialize SD card on CS pin 10
dataFile = SD.open("data.txt", FILE_READ);
while (dataFile.available()) {
char c = dataFile.read();
// process character c
}
dataFile.close();
}
void loop() {}
This code reads a file from the SD card one character at a time until the whole file is read.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Reading one character from the SD card inside the while loop.
- How many times: Once for each character in the file until the end.
Each character read requires a separate SPI communication step, so the total operations grow directly with the file size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 reads |
| 100 | About 100 reads |
| 1000 | About 1000 reads |
Pattern observation: The number of operations grows linearly as the file size increases.
Time Complexity: O(n)
This means the time to read the file grows directly in proportion to the number of characters in the file.
[X] Wrong: "Reading one character is always fast, so the total time doesn't depend on file size."
[OK] Correct: Each character read requires communication over SPI, which takes time. More characters mean more reads and more time.
Understanding how communication time grows with data size helps you design efficient embedded programs and explain your reasoning clearly in technical discussions.
"What if we read data in larger blocks instead of one character at a time? How would the time complexity change?"
