Bird
0
0
Arduinoprogramming~5 mins

IR sensor for obstacle detection in Arduino - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: IR sensor for obstacle detection
O(n)
Understanding Time Complexity

When using an IR sensor for obstacle detection, the program often checks sensor readings repeatedly.

We want to understand how the time spent grows as the program runs longer or checks more times.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


const int irSensorPin = A0;
const int threshold = 500;

void setup() {
  Serial.begin(9600);
}

void loop() {
  int sensorValue = analogRead(irSensorPin);
  if (sensorValue > threshold) {
    Serial.println("Obstacle detected");
  }
  delay(100);
}
    

This code reads the IR sensor value repeatedly and prints a message if an obstacle is detected.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The loop() function runs continuously, reading the sensor each time.
  • How many times: It repeats indefinitely, checking the sensor every 100 milliseconds.
How Execution Grows With Input

Each cycle reads the sensor once and does a simple check.

Input Size (n)Approx. Operations
10 (checks)10 sensor reads and checks
100 (checks)100 sensor reads and checks
1000 (checks)1000 sensor reads and checks

Pattern observation: The number of operations grows directly with the number of sensor checks.

Final Time Complexity

Time Complexity: O(n)

This means the time spent grows linearly with how many times the sensor is checked.

Common Mistake

[X] Wrong: "The sensor reading inside the loop makes the program run in constant time because it's just one line."

[OK] Correct: Even though one reading is simple, the loop repeats many times, so total time grows with the number of checks.

Interview Connect

Understanding how repeated sensor checks affect time helps you explain how embedded programs handle real-time data efficiently.

Self-Check

"What if we added a nested loop to check multiple sensors each cycle? How would the time complexity change?"