Bluetooth with HC-05/HC-06 module in Arduino - Time & Space Complexity
When using Bluetooth modules like HC-05 or HC-06 with Arduino, it's important to understand how the program's running time changes as it processes data.
We want to know how the time to send or receive data grows when the amount of data increases.
Analyze the time complexity of the following code snippet.
#include <SoftwareSerial.h>
SoftwareSerial BTserial(10, 11); // RX | TX
void setup() {
BTserial.begin(9600);
}
void loop() {
while (BTserial.available()) {
char c = BTserial.read();
// Process received character
}
}
This code reads characters sent over Bluetooth one by one and processes them as they arrive.
- Primary operation: The
whileloop reads each character from the Bluetooth buffer. - How many times: It runs once for every character received.
As more characters come in, the loop runs more times, once per character.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 reads and processes |
| 100 | 100 reads and processes |
| 1000 | 1000 reads and processes |
Pattern observation: The time grows directly with the number of characters received.
Time Complexity: O(n)
This means the time to read and process data grows linearly with the amount of data received.
[X] Wrong: "Reading Bluetooth data happens instantly no matter how much data arrives."
[OK] Correct: Each character must be read and processed one by one, so more data means more time spent.
Understanding how data reading time grows helps you design efficient communication in embedded systems, a useful skill in many projects and interviews.
"What if we buffered multiple characters before processing? How would the time complexity change?"