Bird
0
0
Raspberry Piprogramming~5 mins

Multiple I2C devices on same bus in Raspberry Pi - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Multiple I2C devices on same bus
O(n)
Understanding Time Complexity

When using multiple I2C devices on the same bus, it's important to understand how the communication time grows as you add more devices.

We want to know how the total time to communicate changes when the number of devices increases.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


import smbus

bus = smbus.SMBus(1)
addresses = [0x20, 0x21, 0x22]  # I2C device addresses

def read_all_devices():
    for addr in addresses:
        data = bus.read_byte(addr)
        print(f"Data from {hex(addr)}: {data}")

This code reads one byte from each I2C device on the bus and prints it.

Identify Repeating Operations
  • Primary operation: Loop over the list of device addresses to read data.
  • How many times: Once per device in the list.
How Execution Grows With Input

Each device adds one more read operation, so the total time grows directly with the number of devices.

Input Size (n)Approx. Operations
1010 reads
100100 reads
10001000 reads

Pattern observation: The time increases in a straight line as more devices are added.

Final Time Complexity

Time Complexity: O(n)

This means the time to read all devices grows directly in proportion to how many devices are on the bus.

Common Mistake

[X] Wrong: "Adding more devices won't affect total communication time much because I2C is fast."

[OK] Correct: Each device requires its own read operation, so total time adds up linearly with device count.

Interview Connect

Understanding how communication time grows with device count helps you design efficient sensor networks and troubleshoot delays in real projects.

Self-Check

"What if we read multiple bytes from each device instead of one? How would the time complexity change?"