I2C bus architecture (SDA, SCL) in Embedded C - Time & Space Complexity
We want to understand how the time to communicate on an I2C bus changes as we send more data.
How does the number of bits sent affect the total time taken?
Analyze the time complexity of the following code snippet.
// Send one byte over I2C
void i2c_send_byte(uint8_t data) {
for (int i = 0; i < 8; i++) {
// Set SDA line to bit value
SDA = (data & 0x80) ? 1 : 0;
data <<= 1;
// Toggle SCL line to clock the bit
SCL = 1;
delay();
SCL = 0;
delay();
}
}
This code sends one byte (8 bits) over the I2C bus by setting the data line (SDA) and toggling the clock line (SCL) for each bit.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that sends each bit of the byte.
- How many times: Exactly 8 times, once for each bit in the byte.
Each byte sent requires 8 clock cycles. If we send more bytes, the time grows by 8 times the number of bytes.
| Input Size (bytes) | Approx. Operations (bit clocks) |
|---|---|
| 10 | 80 |
| 100 | 800 |
| 1000 | 8000 |
Pattern observation: The time grows linearly with the number of bytes sent.
Time Complexity: O(n)
This means the time to send data grows directly in proportion to the number of bytes you send.
[X] Wrong: "Sending more bytes takes the same time as sending one byte because the clock speed is fixed."
[OK] Correct: Even though the clock speed is fixed, each byte requires multiple clock cycles, so more bytes mean more total time.
Understanding how communication time grows with data size helps you design efficient embedded systems and explain your reasoning clearly in interviews.
"What if we changed the code to send 16 bits instead of 8 bits per data unit? How would the time complexity change?"