Bird
0
0
Arduinoprogramming~5 mins

Reading I2C sensor data in Arduino - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Reading I2C sensor data
O(n)
Understanding Time Complexity

When reading data from an I2C sensor, it's important to know how the time to get data changes as we read more bytes.

We want to understand how the program's work grows when reading sensor data over I2C.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


#include <Wire.h>

void readSensorData(int bytesToRead) {
  Wire.beginTransmission(0x40); // Sensor address
  Wire.write(0x00); // Register to read
  Wire.endTransmission();

  Wire.requestFrom(0x40, bytesToRead);
  while (Wire.available() > 0) {
    byte data = Wire.read();
    // Process data byte
  }
}

This code reads a given number of bytes from an I2C sensor and processes each byte one by one.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The while loop reading each byte from the sensor.
  • How many times: It runs once for each byte requested (bytesToRead times).
How Execution Grows With Input

As the number of bytes to read increases, the loop runs more times, so the total work grows directly with the input size.

Input Size (n)Approx. Operations
10About 10 reads and processes
100About 100 reads and processes
1000About 1000 reads and processes

Pattern observation: The work grows evenly as the number of bytes increases.

Final Time Complexity

Time Complexity: O(n)

This means the time to read and process data grows in a straight line with the number of bytes requested.

Common Mistake

[X] Wrong: "Reading more bytes from the sensor takes the same time no matter how many bytes I read."

[OK] Correct: Each byte requires a separate read operation, so more bytes mean more work and more time.

Interview Connect

Understanding how sensor data reading scales helps you write efficient code for real devices, showing you know how hardware communication affects program speed.

Self-Check

"What if we read data in fixed-size chunks instead of one byte at a time? How would the time complexity change?"