0
0
Raspberry Piprogramming~5 mins

Home automation with relay modules in Raspberry Pi - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Home automation with relay modules
O(n)
Understanding Time Complexity

When controlling home devices with relay modules on a Raspberry Pi, it is important to understand how the time to run the control program changes as you add more devices.

We want to know how the program's work grows when we control many relays.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


relay_pins = [17, 18, 27, 22]
for pin in relay_pins:
    setup_pin(pin, "OUTPUT")

for pin in relay_pins:
    turn_on_relay(pin)
    wait(1)  # wait 1 second
    turn_off_relay(pin)

This code sets up several relay pins and then turns each relay on and off one by one with a delay.

Identify Repeating Operations
  • Primary operation: Looping through the list of relay pins twice.
  • How many times: Once for setup, once for turning relays on and off, each time for every relay.
How Execution Grows With Input

As the number of relays increases, the program runs more setup and control steps, one for each relay.

Input Size (n)Approx. Operations
10About 20 steps (2 loops x 10 relays)
100About 200 steps
1000About 2000 steps

Pattern observation: The total work grows directly with the number of relays; doubling relays doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the program grows in a straight line with the number of relays you control.

Common Mistake

[X] Wrong: "Adding more relays won't affect the time much because each relay works independently."

[OK] Correct: Even if relays work independently, the program still loops through each one, so more relays mean more steps to run.

Interview Connect

Understanding how your program's work grows with more devices shows you can write efficient code for real home automation projects.

Self-Check

"What if we turned on all relays at the same time instead of one by one? How would the time complexity change?"