I2C vs SPI decision matrix in Embedded C - Performance Comparison
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.
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.
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).
As the number of bytes to send increases, the total time grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 byte sends |
| 100 | 100 byte sends |
| 1000 | 1000 byte sends |
Pattern observation: Doubling the data doubles the sending time.
Time Complexity: O(n)
This means the time to send data grows linearly with the number of bytes.
[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.
Understanding how communication time grows with data size helps you explain design choices clearly and shows you grasp practical embedded system trade-offs.
"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?"