Bird
0
0
Arduinoprogramming~5 mins

Servo angle positioning in Arduino - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Servo angle positioning
O(n)
Understanding Time Complexity

When controlling a servo motor, it's important to know how long the program takes to set the angle.

We want to see how the time to position the servo changes as we change the angle or commands.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


#include <Servo.h>
Servo myServo;

void setup() {
  myServo.attach(9);
}

void loop() {
  for (int angle = 0; angle <= 180; angle += 1) {
    myServo.write(angle);
    delay(15);
  }
}
    

This code moves the servo from 0 to 180 degrees in steps of 1 degree, pausing briefly at each step.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that sets the servo angle from 0 to 180 degrees.
  • How many times: It runs 181 times (from 0 to 180 inclusive).
How Execution Grows With Input

As the number of angle steps increases, the total time grows in a straight line.

Input Size (n)Approx. Operations
1010 angle steps, so 10 writes and delays
100100 angle steps, so 100 writes and delays
180181 angle steps, so 181 writes and delays

Pattern observation: The time grows directly with the number of angle steps; doubling steps doubles the time.

Final Time Complexity

Time Complexity: O(n)

This means the time to position the servo grows linearly with the number of angle steps you command.

Common Mistake

[X] Wrong: "Setting the servo angle once takes the same time no matter how many steps I use."

[OK] Correct: Each angle command takes time, so more steps mean more total time, not the same.

Interview Connect

Understanding how loops affect timing helps you write efficient code for hardware control, a useful skill in many projects.

Self-Check

"What if we changed the step size from 1 degree to 5 degrees? How would the time complexity change?"