0
0
Embedded Cprogramming~5 mins

I2C vs SPI decision matrix in Embedded C - Performance Comparison

Choose your learning style9 modes available
Time Complexity: I2C vs SPI decision matrix
O(n)
Understanding Time Complexity

When choosing between I2C and SPI communication in embedded C, it's important to understand how the time to send data grows as the amount of data increases.

We want to know how the communication time changes when sending more bytes over these protocols.

Scenario Under Consideration

Analyze the time complexity of sending data using I2C and SPI protocols.

// Example: Sending data over I2C
void send_i2c_data(uint8_t* data, int length) {
    for (int i = 0; i < length; i++) {
        i2c_write_byte(data[i]);
    }
}

// Example: Sending data over SPI
void send_spi_data(uint8_t* data, int length) {
    for (int i = 0; i < length; i++) {
        spi_write_byte(data[i]);
    }
}

Both functions send each byte one by one over their respective protocols.

Identify Repeating Operations

Both functions use a loop to send bytes one at a time.

  • Primary operation: Sending one byte over I2C or SPI.
  • How many times: Once for each byte in the data array (length times).
How Execution Grows With Input

As the number of bytes to send increases, the total time grows proportionally.

Input Size (n)Approx. Operations
1010 byte sends
100100 byte sends
10001000 byte sends

Pattern observation: Doubling the data doubles the sending time.

Final Time Complexity

Time Complexity: O(n)

This means the time to send data grows linearly with the number of bytes.

Common Mistake

[X] Wrong: "SPI is always faster, so its time complexity is better than I2C."

[OK] Correct: Both protocols send bytes one by one, so their time complexity is the same. Speed differences come from hardware and clock rates, not complexity.

Interview Connect

Understanding how communication time grows with data size helps you explain design choices clearly and shows you grasp practical embedded system trade-offs.

Self-Check

"What if we used DMA (Direct Memory Access) to send data instead of sending byte-by-byte in a loop? How would the time complexity change?"