Bird
0
0

Identify the error in this PIR sensor code snippet and choose the fix:

medium📝 Debug Q14 of 15
Raspberry Pi - gpiozero Library

Identify the error in this PIR sensor code snippet and choose the fix:

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
PIR_PIN = 18
GPIO.setup(PIR_PIN, GPIO.IN)

try:
    while True:
        if GPIO.input(PIR_PIN):
            print("Motion!")
        time.sleep(1)
except KeyboardInterrupt:
    print("Exit")
AUse GPIO.input() outside the loop
BChange GPIO.setup to GPIO.OUT
CRemove time.sleep(1)
DAdd GPIO.cleanup() in except block
Step-by-Step Solution
Solution:
  1. Step 1: Check for GPIO cleanup after program ends

    GPIO pins should be cleaned up to reset their state when the program exits.
  2. Step 2: Add GPIO.cleanup() in the except block

    Adding GPIO.cleanup() ensures pins are properly reset on KeyboardInterrupt.
  3. Final Answer:

    Add GPIO.cleanup() in except block -> Option D
  4. Quick Check:

    Always cleanup GPIO pins on exit [OK]
Quick Trick: Always call GPIO.cleanup() when program ends [OK]
Common Mistakes:
  • Forgetting GPIO.cleanup() causes warnings on rerun
  • Setting input pin as output
  • Removing sleep causes high CPU usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Raspberry Pi Quizzes