Bird
0
0
Raspberry Piprogramming~5 mins

LCD display (16x2) with I2C backpack in Raspberry Pi - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: LCD display (16x2) with I2C backpack
O(n)
Understanding Time Complexity

When working with an LCD display using an I2C backpack on a Raspberry Pi, it's important to understand how the time taken to update the display changes as the amount of data grows.

We want to know how the program's running time changes when we write more characters to the screen.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

from smbus2 import SMBus
import time

bus = SMBus(1)
address = 0x27

def write_string(string):
    for char in string:
        bus.write_byte(address, ord(char))
        time.sleep(0.01)

This code sends each character of a string one by one to the LCD via I2C, pausing briefly after each character.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Loop over each character in the string to send it via I2C.
  • How many times: Once for every character in the input string.
How Execution Grows With Input

As the string gets longer, the number of I2C write operations grows directly with the number of characters.

Input Size (n)Approx. Operations
1010 writes + 10 pauses
100100 writes + 100 pauses
10001000 writes + 1000 pauses

Pattern observation: The time grows steadily and directly with the number of characters sent.

Final Time Complexity

Time Complexity: O(n)

This means the time to send data to the LCD increases in a straight line as the number of characters grows.

Common Mistake

[X] Wrong: "Sending one character or one hundred characters takes the same time because the I2C bus is fast."

[OK] Correct: Each character requires a separate write operation and a small delay, so more characters mean more time spent.

Interview Connect

Understanding how hardware communication time grows with data size helps you write efficient code and explain your design choices clearly.

Self-Check

"What if we removed the delay after each character? How would the time complexity change?"