0
0
Arduinoprogramming~5 mins

Using multiple libraries together in Arduino - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Using multiple libraries together
O(n)
Understanding Time Complexity

When using multiple libraries in Arduino, it's important to understand how the program's running time changes as more libraries are added or used together.

We want to know how the total work grows when combining different library functions.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


#include <Wire.h>
#include <SPI.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup() {
  Wire.begin();
  SPI.begin();
  lcd.init();
  lcd.backlight();
}

void loop() {
  lcd.setCursor(0, 0);
  lcd.print("Hello");
  delay(1000);
}
    

This code uses three libraries to control hardware: Wire for I2C, SPI for SPI communication, and LiquidCrystal_I2C for the LCD display.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The loop() function runs repeatedly, calling lcd.print() each time.
  • How many times: The loop runs forever, repeating the print operation every second.
How Execution Grows With Input

Here, the input size is not a variable like an array length, but the number of library calls and their internal operations.

Input Size (number of library calls)Approx. Operations
1Small number of operations for one library call
3Sum of operations from all three libraries
10Sum grows roughly linearly with number of calls

Pattern observation: The total work grows roughly in a straight line as more library calls are added.

Final Time Complexity

Time Complexity: O(n)

This means the total running time grows linearly with the number of library calls made in the program.

Common Mistake

[X] Wrong: "Adding more libraries does not affect the program speed because they run independently."

[OK] Correct: Each library call adds work that the microcontroller must do, so more libraries or calls increase total execution time.

Interview Connect

Understanding how multiple libraries affect program speed helps you write efficient Arduino code and shows you can think about how different parts of a program work together.

Self-Check

"What if we replaced the lcd.print() call with a function that updates multiple sensors? How would the time complexity change?"