Alarm system with sensor and buzzer in Arduino - Time & Space Complexity
We want to understand how the time the alarm system takes changes as it checks the sensor repeatedly.
How does the program's work grow when it keeps watching the sensor?
Analyze the time complexity of the following code snippet.
const int sensorPin = 2;
const int buzzerPin = 9;
void setup() {
pinMode(sensorPin, INPUT);
pinMode(buzzerPin, OUTPUT);
}
void loop() {
int sensorValue = digitalRead(sensorPin);
if (sensorValue == HIGH) {
digitalWrite(buzzerPin, HIGH);
} else {
digitalWrite(buzzerPin, LOW);
}
}
This code reads a sensor input continuously and turns the buzzer on or off based on the sensor's state.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
loop()function runs forever, repeatedly reading the sensor and setting the buzzer. - How many times: It runs continuously, checking the sensor once every cycle.
Each cycle reads the sensor once and updates the buzzer once, no matter how many times it runs.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 sensor reads and buzzer updates |
| 100 | 100 sensor reads and buzzer updates |
| 1000 | 1000 sensor reads and buzzer updates |
Pattern observation: The work grows directly with the number of cycles; each cycle does a fixed amount of work.
Time Complexity: O(n)
This means the time the program takes grows linearly with how many times it checks the sensor.
[X] Wrong: "The program runs instantly and does not depend on how many times it loops."
[OK] Correct: The program keeps running forever, and the total work grows as it keeps checking the sensor repeatedly.
Understanding how repeated checks affect time helps you explain how embedded systems handle real-time inputs efficiently.
"What if we added a loop inside loop() that checks multiple sensors? How would the time complexity change?"
