SD card module wiring in Arduino - Time & Space Complexity
When working with an SD card module on Arduino, it's important to understand how the wiring affects the speed of communication.
We want to know how the time to read or write data changes as the amount of data grows.
Analyze the time complexity of reading data from an SD card using SPI communication.
#include <SPI.h>
#include <SD.h>
File dataFile;
void setup() {
SD.begin(10); // CS pin 10
dataFile = SD.open("data.txt");
}
void loop() {
if (dataFile) {
while (dataFile.available()) {
char c = dataFile.read();
// process character
}
dataFile.close();
}
while(1); // stop
}
This code reads a file character by character from the SD card connected via SPI.
Look at what repeats as the program runs.
- Primary operation: Reading each character from the SD card inside the while loop.
- How many times: Once for every character in the file until the end.
As the file size grows, the number of characters to read grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 characters | 10 reads |
| 100 characters | 100 reads |
| 1000 characters | 1000 reads |
Pattern observation: The time to read grows directly with the number of characters.
Time Complexity: O(n)
This means the time to read the file grows in a straight line with the file size.
[X] Wrong: "Reading from the SD card takes the same time no matter how big the file is."
[OK] Correct: Each character must be read one by one, so bigger files take more time.
Understanding how data size affects reading time helps you design better programs that handle files efficiently on Arduino.
What if we read the file in larger chunks instead of one character at a time? How would the time complexity change?