Displaying sensor data on screen in Arduino - Time & Space Complexity
When we show sensor data on a screen, the program runs steps repeatedly to update the display.
We want to know how the time it takes grows as we update more data points.
Analyze the time complexity of the following code snippet.
void loop() {
int sensorValue = analogRead(A0);
display.clear();
display.print(sensorValue);
display.update();
delay(1000);
}
This code reads a sensor value, clears the screen, prints the value, updates the display, and waits one second.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop() function runs forever, repeating the steps inside.
- How many times: It repeats once every second, continuously.
Each loop reads one sensor value and updates the screen once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 sensor reads and screen updates |
| 100 | 100 sensor reads and screen updates |
| 1000 | 1000 sensor reads and screen updates |
Pattern observation: The number of operations grows directly with how many times the loop runs.
Time Complexity: O(n)
This means the time to run grows in a straight line as we do more sensor reads and screen updates.
[X] Wrong: "Clearing and updating the display takes constant time no matter how much data we show."
[OK] Correct: If the display shows more data or is more complex, clearing and updating can take longer, so time may grow with data size.
Understanding how repeated sensor reads and screen updates affect time helps you write efficient embedded programs.
"What if we read and display multiple sensor values each loop instead of one? How would the time complexity change?"
