Bird
0
0
Arduinoprogramming~5 mins

Motor direction with H-Bridge (L293D/L298N) in Arduino - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Motor direction with H-Bridge (L293D/L298N)
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each time we increase the loop count, the number of motor commands grows the same amount.

Input Size (n)Approx. Operations
1010 motor direction sets
100100 motor direction sets
10001000 motor direction sets

Pattern observation: The number of operations grows directly with the number of loop repetitions.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Understanding how loops affect execution time helps you write efficient code for hardware control, a useful skill in many projects.

Self-Check

"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?"