i2cdetect for device scanning in Raspberry Pi - Time & Space Complexity
When scanning devices on the I2C bus using i2cdetect, it is important to understand how the time taken grows as the number of addresses checked increases.
We want to know how the scanning time changes when we check more possible device addresses.
Analyze the time complexity of the following code snippet.
for address in range(0x03, 0x78):
try:
bus.write_quick(address)
print(f"Device found at {hex(address)}")
except IOError:
pass
This code scans all possible I2C addresses by trying to communicate with each one to detect if a device responds.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over all possible I2C addresses and attempting communication.
- How many times: Once for each address in the range (about 0x78 - 0x03 = 117 times).
Each additional address checked adds one more communication attempt, so the total work grows directly with the number of addresses.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 communication attempts |
| 100 | 100 communication attempts |
| 1000 | 1000 communication attempts |
Pattern observation: The time grows in a straight line as the number of addresses increases.
Time Complexity: O(n)
This means the scanning time increases directly in proportion to the number of addresses checked.
[X] Wrong: "The scan time stays the same no matter how many addresses we check."
[OK] Correct: Each address requires a communication attempt, so more addresses mean more time spent.
Understanding how scanning time grows helps you reason about device detection efficiency and resource use on embedded systems like Raspberry Pi.
"What if we only scanned a fixed subset of addresses instead of the full range? How would the time complexity change?"
