Connecting multiple I2C devices in Arduino - Time & Space Complexity
When connecting multiple I2C devices, the time to communicate depends on how many devices we talk to.
We want to know how the communication time grows as we add more devices.
Analyze the time complexity of the following code snippet.
#include <Wire.h>
const int deviceCount = 3; // Example device count
const int deviceAddresses[] = {0x20, 0x21, 0x22}; // Example device addresses
const byte data = 0xFF; // Example data to send
void setup() {
Wire.begin();
}
void loop() {
for (int i = 0; i < deviceCount; i++) {
Wire.beginTransmission(deviceAddresses[i]);
Wire.write(data);
Wire.endTransmission();
}
delay(1000);
}
This code sends data to multiple I2C devices one by one in a loop.
- Primary operation: Loop over all devices to send data.
- How many times: Once per device each loop cycle.
Each device adds one more communication step, so time grows steadily with device count.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 transmissions |
| 100 | 100 transmissions |
| 1000 | 1000 transmissions |
Pattern observation: Time increases directly with the number of devices.
Time Complexity: O(n)
This means the time to send data grows in a straight line as you add more devices.
[X] Wrong: "Adding more devices won't affect communication time much because I2C is fast."
[OK] Correct: Each device requires its own communication step, so total time adds up with each device.
Understanding how communication time grows with devices helps you design efficient sensor networks and troubleshoot delays.
"What if we send data to all devices in parallel using multiple I2C buses? How would the time complexity change?"
