Consider this Python Flask code snippet running on a Raspberry Pi to toggle an LED connected to GPIO pin 17. What will be printed when the user accesses the root URL?
from flask import Flask import RPi.GPIO as GPIO app = Flask(__name__) GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.OUT) @app.route('/') def toggle_led(): GPIO.output(17, GPIO.HIGH) print('LED ON') return 'LED is now ON' if __name__ == '__main__': app.run()
Think about what the print statement does and what the Flask route returns.
The print('LED ON') outputs to the console where the Flask app runs. The route returns the string 'LED is now ON' to the browser. So both happen.
You want to create a web interface to toggle a GPIO pin on your Raspberry Pi. Which HTTP method should you use to change the GPIO state?
Consider which HTTP methods are intended for actions that change server state.
POST is used to submit data or cause changes on the server. GET should be safe and idempotent, not changing hardware state.
Look at this Flask app code snippet. It raises a RuntimeError: 'This module can only be run on a Raspberry Pi!'. Why?
from flask import Flask import RPi.GPIO as GPIO app = Flask(__name__) @app.route('/on') def led_on(): GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) GPIO.output(18, GPIO.HIGH) return 'LED ON' if __name__ == '__main__': app.run()
Think about the environment where the code runs and the RPi.GPIO module requirements.
The RPi.GPIO library only works on Raspberry Pi hardware. Running this code on other machines causes RuntimeError.
Choose the correct Flask route code snippet that toggles GPIO pin 22 from LOW to HIGH or HIGH to LOW each time the route is accessed.
Remember GPIO.output expects 0 or 1, and toggling means switching between these states.
Option C explicitly sets output to 1 if input was 0, else 0, correctly toggling the pin. Option C uses 'not state' which returns True/False, not 0/1, causing issues.
Given this Flask app code controlling multiple GPIO pins, how many pins will be HIGH after the '/activate' route is accessed once?
from flask import Flask import RPi.GPIO as GPIO app = Flask(__name__) GPIO.setmode(GPIO.BCM) pins = [5, 6, 13, 19] for pin in pins: GPIO.setup(pin, GPIO.OUT) GPIO.output(pin, GPIO.LOW) @app.route('/activate') def activate(): for pin in pins: if pin % 2 == 1: GPIO.output(pin, GPIO.HIGH) return 'Activated odd pins' if __name__ == '__main__': app.run()
Check which pins in the list are odd numbers.
Pins are 5, 6, 13, 19. Odd pins are 5, 13, 19. 19 % 2 == 1 is True, so pins 5, 13, and 19 are odd. The correct answer is 3.