Using multiple libraries together in Arduino - Time & Space 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.
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 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.
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 |
|---|---|
| 1 | Small number of operations for one library call |
| 3 | Sum of operations from all three libraries |
| 10 | Sum grows roughly linearly with number of calls |
Pattern observation: The total work grows roughly in a straight line as more library calls are added.
Time Complexity: O(n)
This means the total running time grows linearly with the number of library calls made in the program.
[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.
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.
"What if we replaced the lcd.print() call with a function that updates multiple sensors? How would the time complexity change?"