Bird
0
0
Arduinoprogramming~5 mins

Motor speed control with PWM in Arduino - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Motor speed control with PWM
O(n)
Understanding Time 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?

Scenario Under Consideration

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

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

As the speed range increases, the number of loop steps grows directly with it.

Input Size (n)Approx. Operations
1010 steps
100100 steps
255255 steps

Pattern observation: The work grows in a straight line as the speed steps increase.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows directly in proportion to the number of speed steps.

Common Mistake

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

Interview Connect

Understanding how loops and delays affect program time helps you explain how embedded systems handle tasks efficiently.

Self-Check

"What if we replaced the for-loop with a while-loop that increments speed by 5 each time? How would the time complexity change?"