Python Raspberry Pi 上多个 PIR 运动传感器的代码

Python code for multiple PIR motion sensors on Raspberry Pi

为一个项目在 raspberry pi 上连接最多三个 5v 运动传感器,我对 python 还很陌生。我已经成功地编写了一个运动传感器,它会在检测到运动时点亮 LED 并发出蜂鸣声。我如何编写多个传感器然后点亮不同的 LED?

# 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)

您应该为您的传感器创建不同的实例,例如

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

等等。

然后你可以检查

if inp_b == 1

你也可以实现多线程

另外请注意,while 循环之后的最后一行代码将永远不会执行。

如果以后有人想在树莓派 4 上使用一对 P​​IR 运动传感器,上面的代码帮助我解决了这个问题。下面的代码是我如何使用它的。

motion_1 = GPIO.add_event_detect(pirPin, GPIO.RISING, callback=LIGHTS)
motion_2 = GPIO.add_event_detect(pirPin2, GPIO.RISING, callback=LIGHTS2)                                                                                                                                                                            

try:
    while True:
          if motion_1 == 1:
              motion_1
              print('Test for BTC') # print in command line , not LCD
              time.sleep(1)
          elif motion_2 == 1:
              motion_2
              print('Test for eth') # print in command line, not LCD
              time.sleep(1)

except KeyboardInterrupt:
    print('Quit')
    GPIO.cleanup()

 ## the lights function being called above, pulls data from binance API, and prints out the price to an LCD screen, so i can trigger a PIR motion on the left and it returns BTC, i can trigger PIR motion on the right and it returns ETH prices. Kind of fun to build.