Search code examples
pythonraspberry-pi3

Python code for multiple PIR motion sensors on Raspberry Pi


Connecting up to three 5v motion sensors on the raspberry pi for a project and I'm pretty new to python. I've successfully coded one motion sensor which lights up an LED and makes a buzzer sound when motion detected. How would I code multiple sensors that then light up different LEDs?

# Motion detected with buzzer and LED

import RPi.GPIO as GPIO
import time

GPIO.setwarnings(False)

#Refer pins by their sequence number on the board
GPIO.setmode(GPIO.BCM)

#Read output from PIR motion sensor
GPIO.setup(18, GPIO.IN)

#LED output pin
GPIO.setup(3, GPIO.OUT)

while True:
    inp = GPIO.input(18)
#When output from motion sensor is HIGH
    if inp == 1:
    print("Motion detected!!")
    GPIO.output(3, 1) #Turn on LED & Buzzer
    time.sleep(1)

#When output from motion sensor in LOW
    elif inp == 0:
    print("No motion, all okay.")
    GPIO.output(3, 0) #Turn off LED & Buzzer
    time.sleep(1)

time.sleep(0.1)

Solution

  • You should create different instances for your sensors, for instance

    inp_a = GPIO.input(18)
    inp_b = GPIO.input(1x)
    

    and so on.

    then you can check with

    if inp_b == 1
    

    You can implement multithreading as well

    Also, note that your last line of code, after the while loop, will never be executed.