Pull-up and pull-down resistors in Raspberry Pi - Time & Space Complexity
When using pull-up and pull-down resistors with a Raspberry Pi, it's important to understand how the program's speed changes as it reads input signals.
We want to know how the time to read inputs grows when we check many pins or inputs.
Analyze the time complexity of the following code snippet.
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
pins = [17, 18, 27, 22, 23]
for pin in pins:
GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
for pin in pins:
state = GPIO.input(pin)
print(f"Pin {pin} state: {state}")
This code sets up several pins with pull-up resistors and then reads their states one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the list of pins to read their input states.
- How many times: Once for each pin in the list (n times, where n is the number of pins).
Each additional pin adds one more input read operation, so the total work grows directly with the number of pins.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 input reads |
| 100 | 100 input reads |
| 1000 | 1000 input reads |
Pattern observation: The time to read inputs grows in a straight line as the number of pins increases.
Time Complexity: O(n)
This means the time to read all pin states grows directly in proportion to how many pins you check.
[X] Wrong: "Reading multiple pins with pull-up or pull-down resistors happens instantly no matter how many pins there are."
[OK] Correct: Each pin read takes a small amount of time, so more pins mean more total time. It doesn't happen all at once.
Understanding how input reading scales helps you write efficient code for hardware projects, showing you can think about performance even in simple setups.
"What if we read the pins in parallel using interrupts instead of one by one? How would the time complexity change?"