我正在使用树莓派制作简单的门铃报警系统。我做了一个简单的开关,连接到门上。该程序旨在当门打开(HIGH)时通过SMTP向我发送文本,然后在输入返回到低时向我发送另一个文本。
问题在于它为每个警报发送了2个文本。文本上的时间戳显示它们关闭了大约半秒钟。有趣的是,这似乎是pi独有的。我修改了代码,用用户输入的1和0代替GPIO输入,但没有收到重复的文本。下面是我的代码的子集。任何帮助将不胜感激。
另外,电路方面,我正在关闭3,3v PIN 1并在返回PIN 11之前通过1K欧姆电阻运行。
import RPi.GPIO as GPIO
import smtplib
import time
from datetime import datetime, timedelta
from sys import exit
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
doorstatus = 1
def sendalert(msg):
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login('MyEmail', 'Password')
server.sendmail('MyEmail', 'MyNumber@vtext.com', msg)
server.quit()
print msg
return
def doorchange(msg):
etime = str(datetime.now())
etime = etime.split(':')
etime = ",".join(etime)
message = msg + etime
sendalert(message)
return
try:
while True:
time.sleep(1)
if GPIO.input(11) == 1 and doorstatus == 1:
text = "Alert! Door has been opened. "
doorchange(text)
doorstatus = 0
time.sleep(1)
elif GPIO.input(11) == 0 and doorstatus == 0:
text = "Door has been closed. "
doorchange(text)
doorstatus = 1
time.sleep(1)
else:
pass
except KeyboardInterrupt:
GPIO.cleanup()
答案 0 :(得分:0)
这看起来像一个弹跳的问题。这意味着当门打开或关闭时,GPIO状态会在稳定之前在0和1之间变化几次。
这可以通过硬件(使用防跳电路,其中包括与电阻并联的电容)或更容易编程来解决。本文档介绍了如何去抖(参见开关去抖部分):
http://sourceforge.net/p/raspberry-gpio-python/wiki/Inputs/
这当然会让你改变一下你的逻辑:
GPIO.add_event_callback(channel, doorchanged, bouncetime=500)
def doorchanged():
etime = str(datetime.now())
etime = etime.split(':')
etime = ",".join(etime)
if GPIO.input(11) == 1:
text = "Alert! Door has been opened. "
else:
text = "Alert! Door has been closed. "
sendalert(text + etime)