Bird
0
0
Raspberry Piprogramming~5 mins

i2cdetect for device scanning in Raspberry Pi - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: i2cdetect for device scanning
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

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
1010 communication attempts
100100 communication attempts
10001000 communication attempts

Pattern observation: The time grows in a straight line as the number of addresses increases.

Final Time Complexity

Time Complexity: O(n)

This means the scanning time increases directly in proportion to the number of addresses checked.

Common Mistake

[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.

Interview Connect

Understanding how scanning time grows helps you reason about device detection efficiency and resource use on embedded systems like Raspberry Pi.

Self-Check

"What if we only scanned a fixed subset of addresses instead of the full range? How would the time complexity change?"