Motor direction with H-Bridge (L293D/L298N) in Arduino - Time & Space Complexity
When controlling a motor with an H-Bridge, the code runs commands to set motor direction and speed.
We want to see how the time to run this code changes as we repeat motor commands more times.
Analyze the time complexity of the following code snippet.
const int motorPin1 = 3;
const int motorPin2 = 4;
void setup() {
pinMode(motorPin1, OUTPUT);
pinMode(motorPin2, OUTPUT);
}
void loop() {
for (int i = 0; i < 100; i++) {
digitalWrite(motorPin1, HIGH);
digitalWrite(motorPin2, LOW);
delay(1000);
}
}
This code sets motor direction by turning one pin on and the other off repeatedly 100 times, each with a delay.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that runs 100 times.
- How many times: The motor direction commands inside the loop run exactly 100 times.
Each time we increase the loop count, the number of motor commands grows the same amount.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 motor direction sets |
| 100 | 100 motor direction sets |
| 1000 | 1000 motor direction sets |
Pattern observation: The number of operations grows directly with the number of loop repetitions.
Time Complexity: O(n)
This means the time to run the motor commands grows in a straight line as we increase the number of repeats.
[X] Wrong: "The motor commands inside the loop run instantly and don't add to time."
[OK] Correct: Each command takes some time to execute, and repeating them more times adds up linearly.
Understanding how loops affect execution time helps you write efficient code for hardware control, a useful skill in many projects.
"What if we added a nested loop inside the existing loop to run motor commands multiple times per iteration? How would the time complexity change?"
