Bird
0
0

Which code snippet correctly implements this behavior?

hard📝 Application Q15 of 15
Raspberry Pi - GPIO Basics with Python
You want to detect if a motion sensor connected to pin 27 is active (HIGH) and print "Motion detected" only once when it changes from LOW to HIGH. Which code snippet correctly implements this behavior?
AGPIO.setup(27, GPIO.OUT) while True: if GPIO.input(27): print("Motion detected")
BGPIO.setup(27, GPIO.IN) prev_state = False while True: current_state = GPIO.input(27) if current_state and not prev_state: print("Motion detected") prev_state = current_state
CGPIO.setup(27, GPIO.IN) while True: if GPIO.input(27): print("Motion detected")
DGPIO.setup(27, GPIO.IN) prev_state = True while True: current_state = GPIO.input(27) if current_state and not prev_state: print("Motion detected") prev_state = current_state
Step-by-Step Solution
Solution:
  1. Step 1: Setup pin as input and track previous state

    Pin 27 must be set as input. To detect change from LOW to HIGH, store previous state starting as False (LOW).
  2. Step 2: Detect rising edge and print once

    Inside the loop, read current state. If current is True and previous is False, print message once. Then update previous state.
  3. Step 3: Analyze options

    GPIO.setup(27, GPIO.IN) prev_state = False while True: current_state = GPIO.input(27) if current_state and not prev_state: print("Motion detected") prev_state = current_state correctly implements this logic. GPIO.setup(27, GPIO.OUT) while True: if GPIO.input(27): print("Motion detected") sets pin as output, wrong. GPIO.setup(27, GPIO.IN) while True: if GPIO.input(27): print("Motion detected") prints repeatedly while HIGH, not once. GPIO.setup(27, GPIO.IN) prev_state = True while True: current_state = GPIO.input(27) if current_state and not prev_state: print("Motion detected") prev_state = current_state starts prev_state as True, so first detection missed.
  4. Final Answer:

    GPIO.setup(27, GPIO.IN), prev_state = False (rising edge detection) -> Option B
  5. Quick Check:

    Detect rising edge with prev_state = False first [OK]
Quick Trick: Track previous state to detect change from LOW to HIGH [OK]
Common Mistakes:
  • Setting pin as output instead of input
  • Printing repeatedly instead of once
  • Initializing previous state incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Raspberry Pi Quizzes