Wire library for I2C in Arduino - Time & Space Complexity
When using the Wire library for I2C communication, it's important to understand how the time to send or receive data changes as the amount of data grows.
We want to know how the time cost grows when we send more bytes over I2C.
Analyze the time complexity of the following code snippet.
#include <Wire.h>
void sendData(byte address, byte* data, int length) {
Wire.beginTransmission(address);
for (int i = 0; i < length; i++) {
Wire.write(data[i]);
}
Wire.endTransmission();
}
This code sends a list of bytes to a device over I2C using the Wire library.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that calls
Wire.write()for each byte. - How many times: Exactly
lengthtimes, once per byte to send.
As the number of bytes to send increases, the number of write operations grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 writes |
| 100 | 100 writes |
| 1000 | 1000 writes |
Pattern observation: The time grows directly in proportion to the number of bytes sent.
Time Complexity: O(n)
This means the time to send data grows linearly with the number of bytes you send.
[X] Wrong: "Sending more bytes takes the same time as sending just one byte."
[OK] Correct: Each byte requires a separate write operation, so more bytes mean more time spent sending.
Understanding how communication time grows with data size helps you write efficient code and explain your reasoning clearly in technical discussions.
"What if we buffered all bytes first and sent them in one call? How would the time complexity change?"
