LCD cursor positioning in Arduino - Time & Space Complexity
When we move the cursor on an LCD screen using Arduino, the time it takes depends on how the code sets the position.
We want to know how the time to position the cursor changes as the screen size or position changes.
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); // 16 columns, 2 rows
}
void loop() {
lcd.setCursor(5, 1); // Move cursor to column 5, row 1
lcd.print("Hello");
delay(1000);
}
This code moves the cursor to a specific position on a 16x2 LCD and prints text.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The call to
lcd.setCursor(column, row)which sends commands to the LCD controller. - How many times: Once per loop cycle, so it repeats every time
loop()runs.
The time to set the cursor depends on the position but usually is constant because the LCD controller moves the cursor directly.
| Input Size (position) | Approx. Operations |
|---|---|
| Column 5, Row 1 | Constant number of commands sent |
| Column 10, Row 0 | Same constant number of commands sent |
| Column 0, Row 1 | Same constant number of commands sent |
Pattern observation: The time does not grow with the cursor position; it stays about the same.
Time Complexity: O(1)
This means moving the cursor takes the same amount of time no matter where you place it on the screen.
[X] Wrong: "Moving the cursor farther on the screen takes more time because it has to move step by step."
[OK] Correct: The LCD controller receives a direct command to jump to the position, so it does not move stepwise but instantly.
Understanding how hardware commands work and their time cost helps you write efficient code and explain your reasoning clearly in interviews.
"What if we had to move the cursor by sending individual step commands instead of a direct position command? How would the time complexity change?"
