0
0
Arduinoprogramming~5 mins

Receiving commands over Bluetooth in Arduino - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Receiving commands over Bluetooth
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each new command adds one read and one process operation.

Input Size (n)Approx. Operations
1010 reads and 10 processes
100100 reads and 100 processes
10001000 reads and 1000 processes

Pattern observation: The work grows directly with the number of commands received.

Final Time Complexity

Time Complexity: O(n)

This means the time to handle commands grows in a straight line with the number of commands.

Common Mistake

[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.

Interview Connect

Understanding how repeated input handling scales helps you write responsive and efficient programs for real devices.

Self-Check

"What if processCommand took longer for some commands? How would that affect the time complexity?"