运动传感器代码在课堂上使用,并从主班

时间:2017-08-19 08:12:21

标签: python python-2.7 sensor raspberry-pi3

这是我的动作传感器代码



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类中使用上面的代码并从主python类访问它。怎么做?谢谢!

我试过这个

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;




错误

  

追踪(最近一次通话):     File" /home/pi/App/Python2/Main.py" ;,第2行,in       导入PeopleDetector     File" /home/pi/App/Python2/PeopleDetector.py" ;,第5行       GPIO.setmode(GPIO.BCM)       ^   IndentationError:意外缩进

1 个答案:

答案 0 :(得分:0)

Python是一种对空间敏感的语言。您需要使用正确的缩进(制表符/ 4个空格一致)。 if& else声明要求您缩进其下的代码。您拥有的更新代码不包含必要的选项卡。试试这个。

<强> 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()