MotionSensor (PIR) in Raspberry Pi - Time & Space 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.
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 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.
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) |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of operations grows linearly with the time the program runs.
Time Complexity: O(n)
This means the time to run grows directly in proportion to how long the program keeps checking the sensor.
[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.
Understanding how loops that run continuously affect time helps you reason about programs that monitor sensors or devices in real time.
"What if we changed the sleep time from 1 second to 0.1 seconds? How would the time complexity change?"