We use a web interface to control Raspberry Pi's GPIO pins so we can turn devices on or off from any device with a browser. This makes controlling hardware easy and remote.
Controlling GPIO through web interface in Raspberry Pi
from flask import Flask, render_template, request import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(pin_number, GPIO.OUT) app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def control_gpio(): if request.method == 'POST': if request.form.get('action') == 'ON': GPIO.output(pin_number, GPIO.HIGH) else: GPIO.output(pin_number, GPIO.LOW) return render_template('index.html') if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)
Use GPIO.setmode(GPIO.BCM) to refer to pins by their Broadcom number.
Flask is a simple web framework to create web pages and handle button clicks.
GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.OUT) GPIO.output(17, GPIO.HIGH)
from flask import Flask, request app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def home(): if request.method == 'POST': action = request.form['action'] # control GPIO here return '<form method="post"><button name="action" value="ON">ON</button><button name="action" value="OFF">OFF</button></form>'
This program creates a web page with two buttons to turn GPIO pin 17 ON or OFF. When you press a button, the Raspberry Pi changes the pin state accordingly.
from flask import Flask, render_template_string, request import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) pin = 17 GPIO.setup(pin, GPIO.OUT) app = Flask(__name__) html = ''' <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>GPIO Control</title></head> <body> <h1>Control GPIO Pin 17</h1> <form method="post"> <button name="action" value="ON" type="submit">Turn ON</button> <button name="action" value="OFF" type="submit">Turn OFF</button> </form> </body> </html> ''' @app.route('/', methods=['GET', 'POST']) def control(): if request.method == 'POST': if request.form.get('action') == 'ON': GPIO.output(pin, GPIO.HIGH) elif request.form.get('action') == 'OFF': GPIO.output(pin, GPIO.LOW) return render_template_string(html) if __name__ == '__main__': try: app.run(host='0.0.0.0', port=5000) finally: GPIO.cleanup()
Always clean up GPIO pins with GPIO.cleanup() to avoid warnings on next run.
Run the Flask app with sudo if you get permission errors controlling GPIO.
Make sure your Raspberry Pi and your controlling device are on the same network to access the web page.
You can control Raspberry Pi GPIO pins using a simple web page.
Flask helps create the web interface and handle button clicks.
GPIO library controls the hardware pins safely from Python code.
Practice
Solution
Step 1: Understand the role of GPIO pins
GPIO pins allow Raspberry Pi to interact with hardware like LEDs or motors.Step 2: Recognize the benefit of a web interface
A web interface lets users control these pins from any device with a browser, remotely and easily.Final Answer:
To control hardware remotely using a web page -> Option AQuick Check:
Web interface = remote GPIO control [OK]
- Confusing GPIO control with software installation
- Thinking it speeds up the Raspberry Pi
- Assuming it connects to printers
Solution
Step 1: Identify web server libraries
Flask is a lightweight Python web framework used to build web servers.Step 2: Match Flask with GPIO control
Flask can handle web requests to turn GPIO pins on or off via buttons on a webpage.Final Answer:
Flask -> Option CQuick Check:
Flask = web server for GPIO control [OK]
- Choosing data libraries like NumPy or Pandas
- Confusing plotting library Matplotlib with web server
from flask import Flask, request
import RPi.GPIO as GPIO
app = Flask(__name__)
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.OUT)
@app.route('/pin17/<state>')
def pin17(state):
if state == 'on':
GPIO.output(17, GPIO.HIGH)
return 'Pin 17 is ON'
elif state == 'off':
GPIO.output(17, GPIO.LOW)
return 'Pin 17 is OFF'
else:
return 'Invalid state'What will be the output if you visit
/pin17/on in the browser?Solution
Step 1: Analyze the URL parameter
The URL/pin17/onpasses 'on' as thestateargument to the function.Step 2: Check the condition for 'on'
The code checks ifstate == 'on', then sets GPIO pin 17 HIGH and returns 'Pin 17 is ON'.Final Answer:
Pin 17 is ON -> Option BQuick Check:
URL /pin17/on = Pin 17 ON [OK]
- Confusing 'on' with 'off' states
- Expecting an error for valid URL
- Ignoring the return string
from flask import Flask
import RPi.GPIO as GPIO
app = Flask(__name__)
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
@app.route('/pin18/<state>')
def control_pin(state):
if state = 'on':
GPIO.output(18, GPIO.HIGH)
return 'Pin 18 ON'
elif state == 'off':
GPIO.output(18, GPIO.LOW)
return 'Pin 18 OFF'
else:
return 'Invalid'What is the error in this code?
Solution
Step 1: Check the if condition syntax
The lineif state = 'on':uses '=' which is assignment, not comparison.Step 2: Identify correct comparison operator
It should beif state == 'on':to compare values properly.Final Answer:
Using '=' instead of '==' in the if condition -> Option AQuick Check:
Use '==' for comparison, not '=' [OK]
- Confusing assignment '=' with comparison '=='
- Ignoring syntax errors in if statements
- Assuming GPIO setup is missing
@app.route('/led/<state>')
def led_control(state):
if state == 'on':
GPIO.output(22, GPIO.HIGH)
elif state == 'off':
GPIO.output(22, GPIO.LOW)
return f'LED is {state}'Choose the correct HTML buttons to send the commands:
Solution
Step 1: Understand Flask route expects URL with state
The route '/led/<state>' expects 'on' or 'off' in the URL path.Step 2: Check HTML methods to send GET requests
Forms with action URLs send GET requests correctly when submitted, matching the route.Step 3: Compare options
<form action='/led/on'><input type='submit' value='ON'></form><form action='/led/off'><input type='submit' value='OFF'></form> uses forms with action '/led/on' and '/led/off', which matches the Flask route and triggers the function properly.Final Answer:
<form action='/led/on'><input type='submit' value='ON'></form><form action='/led/off'><input type='submit' value='OFF'></form> -> Option DQuick Check:
Forms with correct action URLs = proper GPIO control [OK]
- Using fetch without handling promises
- Using buttons without URL or form action
- Using incorrect URLs that don't match Flask route
Ready to prove it?
Pass the test and this pattern moves unknown
