RPi.GPIO library to interact with GPIO pins."Motion detected!" each time motion is detected.RPi.GPIO library to interact with GPIO pins."Motion detected!" each time motion is detected.RPi.GPIO library as GPIO and set the GPIO mode to GPIO.BCM. Create a variable called pir_pin and set it to 4, which is the GPIO pin number connected to the PIR sensor.Use import RPi.GPIO as GPIO to import the library. Use GPIO.setmode(GPIO.BCM) to set pin numbering. Assign 4 to pir_pin.
GPIO.setup to set the pir_pin as an input pin.Use GPIO.setup(pir_pin, GPIO.IN) to configure the pin as input.
while True loop that reads the PIR sensor state using GPIO.input(pir_pin). If the input is GPIO.HIGH, print "Motion detected!".Use while True: to create an endless loop. Inside, check if GPIO.input(pir_pin) equals GPIO.HIGH. If yes, print the message.
try-except block around the loop to catch KeyboardInterrupt. Inside except, call GPIO.cleanup() to reset GPIO pins. Run the program and observe the output when motion is detected.Use try: before the loop and except KeyboardInterrupt: after. Inside except, call GPIO.cleanup().
What does a PIR MotionSensor detect when connected to a Raspberry Pi?
Which of the following is the correct way to set up a GPIO pin as input for a PIR sensor in Python using RPi.GPIO?
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
# What goes here?
What will be the output of this Python code snippet when the PIR sensor detects motion?
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
PIR_PIN = 4
GPIO.setup(PIR_PIN, GPIO.IN)
if GPIO.input(PIR_PIN):
print("Motion Detected")
else:
print("No Motion")
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")
You want to count how many times motion is detected in 10 seconds using a PIR sensor on GPIO pin 23. Which code snippet correctly implements this?
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
PIR_PIN = 23
GPIO.setup(PIR_PIN, GPIO.IN)
count = 0
start_time = time.time()
while time.time() - start_time < 10:
if GPIO.input(PIR_PIN):
count += 1
time.sleep(0.5) # debounce delay
print(count)
GPIO.cleanup()
Pass the test and this pattern moves unknown