Stepper motor with driver module in Arduino - Time & Space Complexity
When controlling a stepper motor with a driver module, the program runs loops to move the motor step by step.
We want to know how the time the program takes grows as we ask the motor to move more steps.
Analyze the time complexity of the following code snippet.
#include <Stepper.h>
const int stepsPerRevolution = 200;
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
void setup() {
myStepper.setSpeed(60);
}
void loop() {
myStepper.step(stepsPerRevolution);
delay(1000);
}
This code moves the stepper motor one full revolution (200 steps) each loop cycle.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
step()function moves the motor one step at a time inside a loop. - How many times: It repeats exactly the number of steps requested (200 steps here).
Each step command causes the motor to move one step, so the time grows directly with the number of steps.
| Input Size (steps) | Approx. Operations |
|---|---|
| 10 | 10 step moves |
| 100 | 100 step moves |
| 1000 | 1000 step moves |
Pattern observation: If you double the steps, the time roughly doubles too.
Time Complexity: O(n)
This means the time to move the motor grows in a straight line with the number of steps you ask it to move.
[X] Wrong: "The motor moves instantly no matter how many steps I ask for."
[OK] Correct: Each step takes time to complete, so more steps mean more time needed.
Understanding how loops affect time helps you explain how hardware control programs scale with input size.
"What if we changed the code to move the motor half the steps but twice as fast? How would the time complexity change?"
