Bird
0
0
Arduinoprogramming~5 mins

I2C scanner sketch in Arduino - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: I2C scanner sketch
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • 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.
How Execution Grows With Input

As the number of addresses to check grows, the total time grows roughly the same way.

Input Size (n)Approx. Operations
10About 10 address checks
100About 100 address checks
1000About 1000 address checks

Pattern observation: If you double the number of addresses, the work doubles too.

Final Time Complexity

Time Complexity: O(n)

This means the time to scan grows directly in proportion to how many addresses you check.

Common Mistake

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

Interview Connect

Understanding how loops affect time helps you explain how your code scales, a key skill in programming and problem solving.

Self-Check

"What if we only scanned every other address instead of all? How would the time complexity change?"