Bird
0
0

This Flask code snippet is intended to turn GPIO pin 18 ON or OFF via web requests:

medium📝 Debug Q14 of 15
Raspberry Pi - Web Server and API
This Flask code snippet is intended to turn GPIO pin 18 ON or OFF via web requests:
from flask import Flask
import RPi.GPIO as GPIO

app = Flask(__name__)
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)

@app.route('/pin18/')
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?
AUsing '=' instead of '==' in the if condition
BMissing GPIO.setup for pin 18
CFlask app is not created
DNo return statement in the function
Step-by-Step Solution
Solution:
  1. Step 1: Check the if condition syntax

    The line if state = 'on': uses '=' which is assignment, not comparison.
  2. Step 2: Identify correct comparison operator

    It should be if state == 'on': to compare values properly.
  3. Final Answer:

    Using '=' instead of '==' in the if condition -> Option A
  4. Quick Check:

    Use '==' for comparison, not '=' [OK]
Quick Trick: Use '==' to compare, '=' assigns value [OK]
Common Mistakes:
MISTAKES
  • Confusing assignment '=' with comparison '=='
  • Ignoring syntax errors in if statements
  • Assuming GPIO setup is missing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Raspberry Pi Quizzes