2017-08-19 77 views
-1

這是我的運動傳感器代碼類和呼叫運動傳感器代碼使用從主類

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;

錯誤

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

+0

您應該添加在文本中的錯誤,而不是圖像。 –

+0

@AshishNitinPatil親愛的主席先生,我編輯並添加了它。 –

+0

您遇到的錯誤是縮進錯誤。只需在您的if pir.motion_detected語句後添加一個額外的縮進/製表符 –

回答

0

Python是一種對空間敏感的語言。您需要使用正確的縮進(標籤/ 4個空格一致)。 declaratives需要你縮進它們下面的代碼。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() 
+0

它給出同樣的錯誤先生。我的主課是否正確? –

+0

你使用了我準備好的確切代碼嗎?複製粘貼它,因爲您可能會錯過空格/製表符。 –

+0

這是工作..非常感謝您先生!我對python很陌生。再次感謝。 –