Controlling GPIO through web interface in Raspberry Pi - Time & Space Complexity
When controlling GPIO pins through a web interface on a Raspberry Pi, it is important to understand how the program's running time changes as more requests come in or more pins are controlled.
We want to know how the time to handle each web request grows as the number of GPIO pins or commands increases.
Analyze the time complexity of the following code snippet.
from flask import Flask, request
import RPi.GPIO as GPIO
app = Flask(__name__)
GPIO.setmode(GPIO.BCM)
pins = [17, 18, 27]
for pin in pins:
GPIO.setup(pin, GPIO.OUT)
@app.route('/set_pin')
def set_pin():
pin = int(request.args.get('pin'))
state = request.args.get('state')
if pin in pins:
GPIO.output(pin, GPIO.HIGH if state == 'on' else GPIO.LOW)
return 'OK'
This code sets up a small web server that listens for requests to turn specific GPIO pins on or off.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking if the requested pin is in the list of pins (a membership test).
- How many times: This check happens once per web request.
As the number of pins in the list grows, the time to check if a pin is valid grows too, because it searches through the list.
| Input Size (number of pins) | Approx. Operations per Request |
|---|---|
| 3 | 3 checks |
| 10 | 10 checks |
| 100 | 100 checks |
Pattern observation: The time to find the pin grows roughly in direct proportion to the number of pins.
Time Complexity: O(n)
This means the time to handle each request grows linearly with the number of pins being checked.
[X] Wrong: "Checking if a pin is valid is always instant, no matter how many pins there are."
[OK] Correct: When using a list, the program checks each pin one by one, so more pins mean more checks and more time.
Understanding how your code scales with more inputs is a key skill. It shows you can write programs that stay fast even as they handle more data or users.
"What if we changed the list of pins to a set? How would the time complexity change?"