Reading I2C sensor data in Arduino - Time & Space 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.
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 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).
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 |
|---|---|
| 10 | About 10 reads and processes |
| 100 | About 100 reads and processes |
| 1000 | About 1000 reads and processes |
Pattern observation: The work grows evenly as the number of bytes increases.
Time Complexity: O(n)
This means the time to read and process data grows in a straight line with the number of bytes requested.
[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.
Understanding how sensor data reading scales helps you write efficient code for real devices, showing you know how hardware communication affects program speed.
"What if we read data in fixed-size chunks instead of one byte at a time? How would the time complexity change?"
