运动传感器代码在 class 中使用并从主 class 调用

Motion Sensor code use in class and call from main class

这是我的运动传感器代码

from gpiozero import MotionSensor
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(3,GPIO.OUT)

pir = MotionSensor(4)

while True:
    if pir.motion_detected:
        GPIO.output(3,GPIO.HIGH)
        print("Motion detected!")
    
    else:
        GPIO.output(3,GPIO.LOW)

这是输出

Motion detected!
Motion detected!
Motion detected!

帮助 我想在 python class 中使用上面的代码并从主 python class.How 访问它来完成它?谢谢!

我试过了

MainClass.py

import CalculateTime
import PeopleDetector
         
class Application:
      
           PeopleDetector.PIRDetection()

PeopleDetector.py

from gpiozero import MotionSensor
import RPi.GPIO as GPIO
import time

    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)
    GPIO.setup(3,GPIO.OUT)
    pir = MotionSensor(4)

    def PIRDetection():
        if pir.motion_detected:
        GPIO.output(3,GPIO.HIGH)
        print("Motion detected!")
        return 1;
    
        else:
        GPIO.output(3,GPIO.LOW)
        return 0;

错误

Traceback (most recent call last): File "/home/pi/App/Python2/Main.py", line 2, in import PeopleDetector File "/home/pi/App/Python2/PeopleDetector.py", line 5 GPIO.setmode(GPIO.BCM) ^ IndentationError: unexpected indent

Python 是一种 space 敏感语言。您需要使用正确的缩进(tabs / 4-spaces 始终如一)。 ifelse 声明要求您缩进它们下面的代码。您拥有的更新代码不包含必要的选项卡。试试这个。

PeopleDetector.py

from gpiozero import MotionSensor
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(3,GPIO.OUT)
pir = MotionSensor(4)

def PIRDetection():
    if pir.motion_detected:
        GPIO.output(3,GPIO.HIGH)
        print("Motion detected!")
        return 1
    else:
        GPIO.output(3,GPIO.LOW)
        return 0

MainClass.py

import CalculateTime
import PeopleDetector

class Application:
    PeopleDetector.PIRDetection()