Bird
0
0
Arduinoprogramming~5 mins

PIR motion sensor in Arduino - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: PIR motion sensor
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each time the loop runs, it performs a fixed number of steps regardless of input size.

Input Size (n)Approx. Operations
1010 sensor reads and LED updates
100100 sensor reads and LED updates
10001000 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.

Final Time Complexity

Time Complexity: O(n)

This means the total work grows linearly with the number of loop iterations, but each loop cycle takes constant time.

Common Mistake

[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.

Interview Connect

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.

Self-Check

What if we added a delay inside the loop that depends on how long motion is detected? How would the time complexity change?