0
0
Raspberry Piprogramming~5 mins

First GPIO program (LED blink) in Raspberry Pi - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: First GPIO program (LED blink)
O(n)
Understanding Time Complexity

When we write a program to blink an LED on a Raspberry Pi, it runs some instructions repeatedly. Understanding how the time it takes grows helps us know if the program will run smoothly or slow down.

We want to see how the program's running time changes as it blinks more times.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)

for i in range(10):
    GPIO.output(18, GPIO.HIGH)
    time.sleep(1)
    GPIO.output(18, GPIO.LOW)
    time.sleep(1)

GPIO.cleanup()

This code turns an LED on and off 10 times, waiting 1 second each time.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that repeats turning the LED on and off.
  • How many times: Exactly 10 times in this example.
How Execution Grows With Input

Each blink cycle takes a fixed amount of time. If we increase the number of blinks, the total time grows directly with that number.

Input Size (n)Approx. Operations
1010 blink cycles
100100 blink cycles
10001000 blink cycles

Pattern observation: The total time grows in a straight line as the number of blinks increases.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the program grows directly in proportion to how many times the LED blinks.

Common Mistake

[X] Wrong: "The program runs in the same time no matter how many times the LED blinks because each blink is simple."

[OK] Correct: Each blink adds more steps, so more blinks mean more total time. The program takes longer if you blink more times.

Interview Connect

Understanding how repeated actions affect running time is a key skill. It helps you explain how your code behaves when it runs longer or with more data, which is useful in many real projects.

Self-Check

"What if we changed the for-loop to blink the LED forever without stopping? How would the time complexity change?"