Receiving commands over Bluetooth in Arduino - Time & Space Complexity
When receiving commands over Bluetooth, the program often waits and reads data repeatedly.
We want to know how the time spent grows as more commands come in.
Analyze the time complexity of the following code snippet.
void loop() {
if (Serial.available() > 0) {
char command = Serial.read();
processCommand(command);
}
}
This code checks if a Bluetooth command is available, reads one character, and processes it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop() function runs repeatedly, checking for new data.
- How many times: It runs continuously, many times per second, waiting for commands.
Each new command adds one read and one process operation.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 reads and 10 processes |
| 100 | 100 reads and 100 processes |
| 1000 | 1000 reads and 1000 processes |
Pattern observation: The work grows directly with the number of commands received.
Time Complexity: O(n)
This means the time to handle commands grows in a straight line with the number of commands.
[X] Wrong: "The loop only runs once, so time is constant no matter how many commands come."
[OK] Correct: The loop runs over and over, so more commands mean more reads and processing steps.
Understanding how repeated input handling scales helps you write responsive and efficient programs for real devices.
"What if processCommand took longer for some commands? How would that affect the time complexity?"