DC motor with transistor driver in Arduino - Time & Space Complexity
We want to understand how the time the program takes changes as we control a DC motor using a transistor driver in Arduino code.
Specifically, we ask: how does the program's running time grow when we change the input size or control steps?
Analyze the time complexity of the following code snippet.
int motorPin = 9;
void setup() {
pinMode(motorPin, OUTPUT);
}
void loop() {
analogWrite(motorPin, 255); // turn motor on full speed
delay(1000); // run for 1 second
analogWrite(motorPin, 0); // turn motor off
delay(1000); // wait for 1 second
}
This code turns a DC motor on and off repeatedly using a transistor driver connected to pin 9.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
loop()function runs repeatedly forever. - How many times: It repeats endlessly, turning the motor on and off each cycle.
Here, the program runs the same steps over and over, regardless of input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Same fixed steps repeated 10 times |
| 100 | Same fixed steps repeated 100 times |
| 1000 | Same fixed steps repeated 1000 times |
Pattern observation: The time per cycle stays the same; total time grows linearly with how many cycles run.
Time Complexity: O(1)
This means each cycle of turning the motor on and off takes a fixed amount of time, no matter what.
[X] Wrong: "The time to run the motor depends on the input size or speed value."
[OK] Correct: The code runs fixed delay times and fixed commands each cycle, so time per cycle does not change with input size.
Understanding how loops and delays affect program timing helps you explain how embedded systems control hardware efficiently.
"What if we replaced the fixed delay with a loop that runs n times? How would the time complexity change?"
