Servo motor control with Servo library in Arduino - Time & Space Complexity
When controlling a servo motor using the Servo library, it is helpful to understand how the time the program takes changes as we send commands repeatedly.
We want to know how the program's running time grows when we move the servo many times.
Analyze the time complexity of the following code snippet.
#include <Servo.h>
Servo myServo;
void setup() {
myServo.attach(9);
}
void loop() {
for (int pos = 0; pos <= 180; pos += 1) {
myServo.write(pos);
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 moves the servo position from 0 to 180 degrees.
- How many times: It runs 181 times each time the loop() function runs.
As the number of positions to move the servo increases, the total time grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 servo moves and delays |
| 100 | 100 servo moves and delays |
| 180 | 181 servo moves and delays |
Pattern observation: The time grows linearly as the number of servo positions increases.
Time Complexity: O(n)
This means the time to complete the servo movements grows directly in proportion to the number of positions you move through.
[X] Wrong: "The delay inside the loop does not affect the time complexity because it's just waiting."
[OK] Correct: Even though delay pauses the program, it still adds to the total time the program takes, so it grows with the number of loop steps.
Understanding how loops and delays affect program time helps you explain how your code behaves in real devices, showing you can think about efficiency in embedded systems.
"What if we changed the step size from 1 degree to 10 degrees? How would the time complexity change?"
