Motor speed control with PWM in Arduino - Time & Space Complexity
We want to see how the time the program takes changes as we adjust motor speed control using PWM.
How does the program's work grow when we change the input size or speed settings?
Analyze the time complexity of the following code snippet.
const int motorPin = 9;
void setup() {
pinMode(motorPin, OUTPUT);
}
void loop() {
for (int speed = 0; speed <= 255; speed++) {
analogWrite(motorPin, speed);
delay(10);
}
}
This code gradually increases motor speed from 0 to 255 using PWM signals.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that runs from speed 0 to 255.
- How many times: It runs 256 times each time the loop() function runs.
As the speed range increases, the number of loop steps grows directly with it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps |
| 100 | 100 steps |
| 255 | 255 steps |
Pattern observation: The work grows in a straight line as the speed steps increase.
Time Complexity: O(n)
This means the time to run grows directly in proportion to the number of speed steps.
[X] Wrong: "The delay inside the loop does not affect the time complexity."
[OK] Correct: The delay adds fixed time per step, so total time grows with the number of steps, affecting overall time.
Understanding how loops and delays affect program time helps you explain how embedded systems handle tasks efficiently.
"What if we replaced the for-loop with a while-loop that increments speed by 5 each time? How would the time complexity change?"
