0
0
Raspberry Piprogramming~5 mins

MotionSensor (PIR) in Raspberry Pi - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: MotionSensor (PIR)
O(n)
Understanding Time Complexity

When working with a MotionSensor (PIR) on a Raspberry Pi, it is important to understand how the program's running time changes as it checks for motion repeatedly.

We want to know how the time needed grows as the sensor keeps checking for motion over time.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
PIR_PIN = 7
GPIO.setup(PIR_PIN, GPIO.IN)

while True:
    if GPIO.input(PIR_PIN):
        print("Motion Detected!")
    time.sleep(1)

This code continuously checks the PIR sensor every second and prints a message if motion is detected.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The while loop that repeatedly reads the sensor input.
  • How many times: It runs indefinitely, checking once every second.
How Execution Grows With Input

As time passes, the program keeps checking the sensor once every second, so the number of checks grows directly with time.

Input Size (seconds)Approx. Operations (checks)
1010 checks
100100 checks
10001000 checks

Pattern observation: The number of operations grows linearly with the time the program runs.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows directly in proportion to how long the program keeps checking the sensor.

Common Mistake

[X] Wrong: "The program only runs once, so time complexity is constant."

[OK] Correct: The program runs an endless loop checking the sensor repeatedly, so the time grows as it keeps running.

Interview Connect

Understanding how loops that run continuously affect time helps you reason about programs that monitor sensors or devices in real time.

Self-Check

"What if we changed the sleep time from 1 second to 0.1 seconds? How would the time complexity change?"