16x2 LCD with LiquidCrystal library in Arduino - Time & Space Complexity
When using a 16x2 LCD with the LiquidCrystal library, it's helpful to know how the time to update the display changes as we write more characters.
We want to understand how the program's running time grows when printing text on the LCD.
Analyze the time complexity of the following code snippet.
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup() {
lcd.begin(16, 2);
for (int i = 0; i < 32; i++) {
lcd.print('*');
}
}
void loop() {}
This code initializes a 16x2 LCD and prints 32 stars, filling both lines of the display.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that calls
lcd.print('*')32 times. - How many times: Exactly 32 times, once for each character printed on the LCD.
Each character printed takes roughly the same time, so the total time grows as we print more characters.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print calls |
| 100 | 100 print calls |
| 1000 | 1000 print calls |
Pattern observation: The time grows directly with the number of characters printed; doubling characters doubles time.
Time Complexity: O(n)
This means the time to print grows in a straight line with the number of characters you send to the LCD.
[X] Wrong: "Printing multiple characters at once is as fast as printing one character."
[OK] Correct: Each character requires communication with the LCD, so printing many characters takes proportionally more time.
Understanding how loops and repeated operations affect time helps you write efficient code for devices like LCDs, showing you can think about performance in real projects.
"What if we replaced the for-loop with a function that prints a whole string at once? How would the time complexity change?"
