Servo angle positioning in Arduino - Time & Space 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.
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 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).
As the number of angle steps increases, the total time grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 angle steps, so 10 writes and delays |
| 100 | 100 angle steps, so 100 writes and delays |
| 180 | 181 angle steps, so 181 writes and delays |
Pattern observation: The time grows directly with the number of angle steps; doubling steps doubles the time.
Time Complexity: O(n)
This means the time to position the servo grows linearly with the number of angle steps you command.
[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.
Understanding how loops affect timing helps you write efficient code for hardware control, a useful skill in many projects.
"What if we changed the step size from 1 degree to 5 degrees? How would the time complexity change?"
