gpt4 book ai didi

python - PIR 传感器运动检测计数写入 python 中的文本文件

转载 作者:太空宇宙 更新时间:2023-11-04 05:59:46 25 4
gpt4 key购买 nike

我需要将“pir 传感器”运动检测 COUNT 写入文本文件。

我尝试使用此代码,无需写入文本文件即可工作。当我写入文件时出现错误 file = open("textFile.txt", "w")IndentationError: unindent does not matchanyouter indentation level.预期输出是文本文件中的最后一个运动计数。

代码是

    # Import required Python libraries
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
# Define GPIO to use on Pi
GPIO_PIR = 7
# Set pin as input

GPIO.setup(GPIO_PIR,GPIO.IN)


Current_State = 0

Previous_State = 0

# I put Variable= 0 for the motion Count
Variable= 0
try:
print "Waiting for PIR to settle ..."

# Loop until PIR output is 0
while GPIO.input(GPIO_PIR)==1:
Current_State = 0
print " Ready"
# Loop until users quits with CTRL-C
while True :

# Read PIR state
Current_State = GPIO.input(GPIO_PIR)

if Current_State==1 and Previous_State==0:
# PIR is triggered
start_time=time.time()
print " Motion detected!"

# here I need to write numbers for the text file.
file = open("textFile.txt", "w")
file.write(Variable)
file.close()
Variable+=1

# Record previous state
Previous_State=1
elif Current_State==0 and Previous_State==1:
# PIR has returned to ready state
stop_time=time.time()
print " Ready ",
elapsed_time=int(stop_time-start_time)
print " (Elapsed time : " + str(elapsed_time) + " secs)"
Previous_State=0

except KeyboardInterrupt:
print " Quit"
# Reset GPIO settings
GPIO.cleanup()

最佳答案

import RPi.GPIO as GPIO
import time

# Use BCM GPIO references
# instead of physical pin numbers
GPIO.setmode(GPIO.BCM)

# Define GPIO to use on Pi
GPIO_PIR = 7

print "PIR Module Test (CTRL-C to exit)"

# Set pin as input
GPIO.setup(GPIO_PIR,GPIO.IN) # Echo

Current_State = 0
Previous_State = 0
Variable=0

try:

print "Waiting for PIR to settle ..."

# Loop until PIR output is 0
while GPIO.input(GPIO_PIR)==1:
Current_State = 0

print " Ready"

# Loop until users quits with CTRL-C
while True :

# Read PIR state
Current_State = GPIO.input(GPIO_PIR)

if Current_State==1 and Previous_State==0:
# PIR is triggered
print " Motion detected!"
# Record previous state
Previous_State=1
file = open("textFile.txt", "w")
file.write(Variable)
file.close()
Variable+=1
elif Current_State==0 and Previous_State==1:
# PIR has returned to ready state
print " Ready"
Previous_State=0

# Wait for 10 milliseconds
time.sleep(0.01)

except KeyboardInterrupt:
print " Quit"
# Reset GPIO settings

这是我 friend 的代码。(我相信你的代码没有任何问题,但有一些缩进错误(例如间距错误)为此你可以使用某种文本编辑器(我使用 sublime text)

关于python - PIR 传感器运动检测计数写入 python 中的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25751050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com