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

2024-10-02 20:42:24 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的运动传感器代码

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)

这是输出

帮助 我想在python类中使用上面的代码,并从主python访问它同学们,怎么了去做吗?谢谢您!在

我试过了

主类.py

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

人检测器.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


Tags: 代码frompyimportoutputgpioasrpi
1条回答
网友
1楼 · 发布于 2024-10-02 20:42:24

Python是一种空间敏感语言。您需要使用正确的缩进(制表符/4-空格一致)。if&;else声明要求您缩进它们下面的代码。更新后的代码不包含必需的制表符。试试这个。在

人检测器.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

主类.py

^{pr2}$

相关问题 更多 >