Sending data over Bluetooth in Arduino - Time & Space Complexity
When sending data over Bluetooth with Arduino, it's important to know how the time to send grows as the data size grows.
We want to understand how the program's running time changes when we send more data.
Analyze the time complexity of the following code snippet.
void sendData(char* data, int length) {
for (int i = 0; i < length; i++) {
Serial.write(data[i]);
}
}
This code sends each byte of data one by one over Bluetooth using Serial.write.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Sending each byte with Serial.write inside a for loop.
- How many times: The loop runs once for every byte in the data (length times).
As the amount of data grows, the number of send operations grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 send operations |
| 100 | 100 send operations |
| 1000 | 1000 send operations |
Pattern observation: The time to send data grows directly with the number of bytes.
Time Complexity: O(n)
This means the time to send data grows in a straight line as the data size grows.
[X] Wrong: "Sending data over Bluetooth happens instantly no matter the size."
[OK] Correct: Each byte takes time to send, so sending more bytes takes more time.
Understanding how sending data scales helps you write efficient code for devices that communicate wirelessly.
"What if we send data in chunks instead of byte by byte? How would the time complexity change?"