I2C scanner sketch in Arduino - Time & Space Complexity
We want to understand how the time to run an I2C scanner changes as it checks more addresses.
How does the number of addresses affect the total work done?
Analyze the time complexity of the following code snippet.
#include <Wire.h>
void setup() {
Wire.begin();
Serial.begin(9600);
for (byte address = 1; address <= 127; address++) {
Wire.beginTransmission(address);
byte error = Wire.endTransmission();
if (error == 0) {
Serial.print("Device found at address 0x");
Serial.println(address, HEX);
}
}
}
void loop() {}
This code scans all possible I2C addresses to find connected devices by trying to start communication with each address.
- Primary operation: The for-loop that tries to communicate with each I2C address.
- How many times: It runs once for each address from 1 to 127, so about 127 times.
As the number of addresses to check grows, the total time grows roughly the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 address checks |
| 100 | About 100 address checks |
| 1000 | About 1000 address checks |
Pattern observation: If you double the number of addresses, the work doubles too.
Time Complexity: O(n)
This means the time to scan grows directly in proportion to how many addresses you check.
[X] Wrong: "The scanner checks all addresses instantly, so time does not depend on number of addresses."
[OK] Correct: Each address requires a communication attempt, which takes time, so more addresses mean more total time.
Understanding how loops affect time helps you explain how your code scales, a key skill in programming and problem solving.
"What if we only scanned every other address instead of all? How would the time complexity change?"
