0
0
Raspberry Piprogramming~30 mins

MotionSensor (PIR) in Raspberry Pi - Mini Project: Build & Apply

Choose your learning style9 modes available
MotionSensor (PIR) with Raspberry Pi
📖 Scenario: You have a Raspberry Pi connected to a PIR motion sensor. The sensor detects movement in a room and sends a signal to the Pi. You want to write a simple program to read the sensor's signal and print a message when motion is detected.
🎯 Goal: Build a Python program that reads input from a PIR motion sensor connected to the Raspberry Pi's GPIO pin and prints "Motion detected!" when movement is sensed.
📋 What You'll Learn
Use the RPi.GPIO library to interact with GPIO pins.
Set up the GPIO pin connected to the PIR sensor as input.
Detect when the PIR sensor output goes HIGH (motion detected).
Print "Motion detected!" each time motion is detected.
💡 Why This Matters
🌍 Real World
Motion sensors are used in home security systems, automatic lighting, and energy-saving applications to detect presence and movement.
💼 Career
Understanding how to read sensor input and control GPIO pins is essential for embedded systems, IoT development, and hardware interfacing jobs.
Progress0 / 4 steps
1
Set up GPIO and PIR sensor pin
Import the 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.
Raspberry Pi
Need a hint?

Use import RPi.GPIO as GPIO to import the library. Use GPIO.setmode(GPIO.BCM) to set pin numbering. Assign 4 to pir_pin.

2
Configure PIR pin as input
Use GPIO.setup to set the pir_pin as an input pin.
Raspberry Pi
Need a hint?

Use GPIO.setup(pir_pin, GPIO.IN) to configure the pin as input.

3
Detect motion with a loop
Write a while True loop that reads the PIR sensor state using GPIO.input(pir_pin). If the input is GPIO.HIGH, print "Motion detected!".
Raspberry Pi
Need a hint?

Use while True: to create an endless loop. Inside, check if GPIO.input(pir_pin) equals GPIO.HIGH. If yes, print the message.

4
Clean up GPIO on exit and run program
Add a 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.
Raspberry Pi
Need a hint?

Use try: before the loop and except KeyboardInterrupt: after. Inside except, call GPIO.cleanup().