WiFi with ESP8266/ESP32 in Arduino - Time & Space Complexity
When using WiFi on ESP32, it's important to understand how the time to connect and send data changes as the program runs.
We want to know how the program's running time grows when it tries to connect or send data over WiFi.
Analyze the time complexity of the following code snippet.
#include <WiFi.h>
const char* ssid = "MyNetwork";
const char* password = "MyPassword";
void setup() {
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
}
void loop() {
// main code
}
This code tries to connect the ESP board to a WiFi network by repeatedly checking the connection status until it succeeds.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that checks if WiFi is connected.
- How many times: It repeats until the connection is established, which depends on network conditions.
Here, the "input" is the time or attempts needed to connect to WiFi, which can vary.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 (attempts) | 10 checks of WiFi status |
| 100 (attempts) | 100 checks of WiFi status |
| 1000 (attempts) | 1000 checks of WiFi status |
Pattern observation: The number of operations grows directly with the number of connection attempts.
Time Complexity: O(n)
This means the time to connect grows linearly with the number of attempts made to check the connection.
[X] Wrong: "The connection will always happen instantly, so the loop runs only once."
[OK] Correct: WiFi connection depends on many factors like signal strength and network response, so the loop may run many times before connecting.
Understanding how loops behave when waiting for hardware or network responses is a useful skill. It shows you can think about how long your code might take in real situations.
"What if we added a timeout to stop trying after a fixed number of attempts? How would the time complexity change?"