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:
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).
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.
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.