Multiple I2C devices on same bus in Raspberry Pi - Time & Space 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.
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.
- Primary operation: Loop over the list of device addresses to read data.
- How many times: Once per device in the list.
Each device adds one more read operation, so the total time grows directly with the number of devices.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 reads |
| 100 | 100 reads |
| 1000 | 1000 reads |
Pattern observation: The time increases in a straight line as more devices are added.
Time Complexity: O(n)
This means the time to read all devices grows directly in proportion to how many devices are on the bus.
[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.
Understanding how communication time grows with device count helps you design efficient sensor networks and troubleshoot delays in real projects.
"What if we read multiple bytes from each device instead of one? How would the time complexity change?"
