0
0
Arduinoprogramming~5 mins

Documentation and pin mapping in Arduino - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Documentation and pin mapping
O(n)
Understanding Time Complexity

When working with Arduino, knowing how your code uses pins and how you document it helps keep things clear and organized.

We want to see how the time your program takes grows as you add more pins or documentation steps.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


const int ledPins[] = {2, 3, 4, 5};

void setup() {
  for (int i = 0; i < 4; i++) {
    pinMode(ledPins[i], OUTPUT); // Set each pin as output
  }
}

void loop() {
  for (int i = 0; i < 4; i++) {
    digitalWrite(ledPins[i], HIGH); // Turn LED on
    delay(500);
    digitalWrite(ledPins[i], LOW);  // Turn LED off
  }
}
    

This code sets up four LED pins and turns each LED on and off in sequence with a delay.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loops that go through each LED pin to set mode and toggle state.
  • How many times: Each loop runs once per LED pin, so 4 times here, but this number can grow with more pins.
How Execution Grows With Input

As you add more pins, the loops run more times, so the work grows with the number of pins.

Input Size (n)Approx. Operations
10About 10 times the loop actions
100About 100 times the loop actions
1000About 1000 times the loop actions

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

Final Time Complexity

Time Complexity: O(n)

This means the time your program takes grows in a straight line as you add more pins to control.

Common Mistake

[X] Wrong: "Adding more pins won't affect how long the code takes because each pin is handled separately."

[OK] Correct: Even though pins are handled one by one, the total time adds up because each pin needs its own setup and control steps.

Interview Connect

Understanding how your code scales with the number of pins shows you can write clear, organized programs that work well as projects grow.

Self-Check

"What if we changed the code to control two LEDs at the same time inside the loop? How would the time complexity change?"