Bird
0
0
Arduinoprogramming~5 mins

Alarm system with sensor and buzzer in Arduino - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Alarm system with sensor and buzzer
O(n)
Understanding Time 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?

Scenario Under Consideration

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

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

Each cycle reads the sensor once and updates the buzzer once, no matter how many times it runs.

Input Size (n)Approx. Operations
1010 sensor reads and buzzer updates
100100 sensor reads and buzzer updates
10001000 sensor reads and buzzer updates

Pattern observation: The work grows directly with the number of cycles; each cycle does a fixed amount of work.

Final Time Complexity

Time Complexity: O(n)

This means the time the program takes grows linearly with how many times it checks the sensor.

Common Mistake

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

Interview Connect

Understanding how repeated checks affect time helps you explain how embedded systems handle real-time inputs efficiently.

Self-Check

"What if we added a loop inside loop() that checks multiple sensors? How would the time complexity change?"