Bird
Raised Fist0
Raspberry Piprogramming~10 mins

MotionSensor (PIR) in Raspberry Pi - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - MotionSensor (PIR)
Start Program
↓
Setup GPIO Pin
↓
Wait for Motion
↓
Motion Detected?
No→Keep Waiting
Yes↓
Print "Motion Detected!"
↓
Repeat Waiting
The program sets up the sensor pin, waits for motion, prints a message when motion is detected, then continues waiting.
Execution Sample
Raspberry Pi
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN)

while True:
    if GPIO.input(17):
        print("Motion Detected!")
        time.sleep(1)
This code waits for motion on GPIO pin 17 and prints a message when motion is detected.
Execution Table
StepGPIO.input(17)Condition (Motion Detected?)ActionOutput
1FalseNoWait
2FalseNoWait
3TrueYesPrint messageMotion Detected!
4FalseNoWait
5TrueYesPrint messageMotion Detected!
💡 Program runs indefinitely, continuously checking for motion.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5
GPIO.input(17)N/AFalseFalseTrueFalseTrue
Key Moments - 2 Insights
Why does the program keep printing "Motion Detected!" multiple times?
Because the loop continuously checks the sensor state and prints whenever motion is detected (see execution_table steps 3 and 5). To avoid repeated prints, you would add a delay or state check.
What happens if GPIO.input(17) is False?
The program does nothing and keeps waiting (see execution_table steps 1, 2, and 4). It only acts when the sensor detects motion.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of GPIO.input(17) at step 3?
AFalse
BTrue
CNone
DError
💡 Hint
Check the 'GPIO.input(17)' column at step 3 in the execution_table.
At which step does the program print "Motion Detected!" for the first time?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Output' column in the execution_table to find when the message first appears.
If GPIO.input(17) never becomes True, what will the program do?
AKeep waiting without printing
BPrint "Motion Detected!" once
CPrint "Motion Detected!" repeatedly
DCrash with error
💡 Hint
Refer to execution_table steps where GPIO.input(17) is False and see the action taken.
Concept Snapshot
MotionSensor (PIR) on Raspberry Pi:
- Setup GPIO pin as input
- Loop: read sensor state
- If motion detected (input True), print message
- Repeat indefinitely
- Use delays or state flags to avoid repeated prints
Full Transcript
This program uses a PIR motion sensor connected to GPIO pin 17 on a Raspberry Pi. It sets up the pin as input and enters an infinite loop. Each loop iteration reads the sensor state. If motion is detected (GPIO.input(17) returns True), it prints "Motion Detected!". Otherwise, it waits silently. The program keeps checking continuously, printing the message each time motion is detected. Beginners often wonder why the message prints multiple times; this happens because the loop runs fast and prints every time the sensor is active. To prevent this, you can add a delay or track previous state. The execution table shows the sensor state and program actions step by step.

Practice

(1/5)
1.

What does a PIR MotionSensor detect when connected to a Raspberry Pi?

easy
A. Temperature changes in the room
B. Sound levels around the sensor
C. Movement by sensing infrared changes
D. Light intensity variations

Solution

  1. Step 1: Understand PIR sensor function

    A PIR sensor detects motion by sensing changes in infrared radiation emitted by objects.
  2. Step 2: Compare options with sensor purpose

    Only Movement by sensing infrared changes matches the PIR sensor's function of detecting movement via infrared changes.
  3. Final Answer:

    Movement by sensing infrared changes -> Option C
  4. Quick Check:

    PIR sensor = Movement detection [OK]
Hint: PIR sensors detect motion, not temperature or sound [OK]
Common Mistakes:
  • Confusing PIR with temperature sensors
  • Thinking PIR detects sound or light
  • Assuming PIR measures humidity
2.

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?
easy
A. GPIO.setup(17, GPIO.IN)
B. GPIO.setup(17, GPIO.OUT)
C. GPIO.input(17)
D. GPIO.output(17, GPIO.HIGH)

Solution

  1. Step 1: Identify pin mode for PIR sensor input

    PIR sensor output should be read as input on the Raspberry Pi GPIO pin.
  2. Step 2: Match correct GPIO setup syntax

    GPIO.setup(pin_number, GPIO.IN) sets the pin as input, which is needed to read sensor data.
  3. Final Answer:

    GPIO.setup(17, GPIO.IN) -> Option A
  4. Quick Check:

    GPIO input setup = GPIO.setup(pin, GPIO.IN) [OK]
Hint: Use GPIO.IN to read sensor signals, not GPIO.OUT [OK]
Common Mistakes:
  • Using GPIO.OUT instead of GPIO.IN
  • Calling GPIO.input() instead of GPIO.setup() to configure pin
  • Trying to write output to sensor pin
3.

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")
medium
A. Motion Detected
B. No Motion
C. SyntaxError
D. GPIO pin not set

Solution

  1. Step 1: Understand GPIO.input behavior

    GPIO.input(PIR_PIN) returns True (1) if motion is detected, False (0) otherwise.
  2. Step 2: Analyze if condition with PIR sensor detecting motion

    If motion is detected, GPIO.input returns True, so the code prints "Motion Detected".
  3. Final Answer:

    Motion Detected -> Option A
  4. Quick Check:

    GPIO.input True = Motion Detected [OK]
Hint: GPIO.input True means motion detected, prints accordingly [OK]
Common Mistakes:
  • Assuming GPIO.input returns string
  • Confusing True/False logic in if statement
  • Not setting up GPIO pin before reading
4.

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")
medium
A. Use GPIO.input() outside the loop
B. Change GPIO.setup to GPIO.OUT
C. Remove time.sleep(1)
D. Add GPIO.cleanup() in except block

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]
Hint: 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
5.

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()
hard
A. Does not count because GPIO pin is not set as output
B. Counts motion detections with debounce, prints count after 10 seconds
C. Counts continuously without delay, causing multiple counts per motion
D. Infinite loop without exit condition

Solution

  1. Step 1: Analyze loop timing and counting logic

    The loop runs for 10 seconds, checking PIR input and incrementing count on detection.
  2. Step 2: Understand debounce with time.sleep(0.5)

    The 0.5 second sleep prevents counting the same motion multiple times quickly.
  3. Step 3: Confirm GPIO cleanup and print

    After loop ends, count is printed and GPIO.cleanup() resets pins properly.
  4. Final Answer:

    Counts motion detections with debounce, prints count after 10 seconds -> Option B
  5. Quick Check:

    Debounce delay + timed loop = correct count [OK]
Hint: Use sleep to debounce and time.time() for timed loops [OK]
Common Mistakes:
  • Missing debounce causes inflated counts
  • Setting pin as output instead of input
  • No exit condition causes infinite loop
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard