PIR motion sensor in Arduino - Time & Space Complexity
When using a PIR motion sensor with Arduino, the program often checks sensor input repeatedly.
We want to understand how the time the program takes grows as it keeps checking the sensor.
Analyze the time complexity of the following code snippet.
int sensorPin = 2;
int ledPin = 13;
void setup() {
pinMode(sensorPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
int motion = digitalRead(sensorPin);
if (motion == HIGH) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}
This code reads the PIR sensor repeatedly and turns an LED on or off based on motion detection.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
loop()function runs forever, repeatedly reading the sensor. - How many times: It runs continuously, checking the sensor once every cycle.
Each time the loop runs, it performs a fixed number of steps regardless of input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 sensor reads and LED updates |
| 100 | 100 sensor reads and LED updates |
| 1000 | 1000 sensor reads and LED updates |
Pattern observation: The number of operations grows directly with how many times the loop runs, but each loop does the same fixed work.
Time Complexity: O(n)
This means the total work grows linearly with the number of loop iterations, but each loop cycle takes constant time.
[X] Wrong: "The time to read the sensor grows if motion is detected because the LED turns on."
[OK] Correct: Turning the LED on or off is a simple command and takes the same time regardless of sensor state, so the time per loop stays constant.
Understanding how repeated sensor checks affect program speed helps you write efficient embedded code and shows you can think about how programs behave over time.
What if we added a delay inside the loop that depends on how long motion is detected? How would the time complexity change?
