IR sensor for obstacle detection in Arduino - Time & Space 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.
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 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.
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.
Time Complexity: O(n)
This means the time spent grows linearly with how many times the sensor is checked.
[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.
Understanding how repeated sensor checks affect time helps you explain how embedded programs handle real-time data efficiently.
"What if we added a nested loop to check multiple sensors each cycle? How would the time complexity change?"
