2015-12-24 52 views
-1

我正在使用樹莓派的一個簡單的門報警系統。我做了一個連接在門上的簡單開關。該程序旨在通過SMTP向我發送文本,當門打開時(HIGH),然後當輸入返回到低時向我發送另一文本。Python SMTP在Raspberry Pi上發送重複電子郵件

問題是,它爲每個警報發送2個文本。文本上的時間標記顯示它們將被關閉約半秒鐘。有趣的是,這似乎是獨一無二的。我修改了代碼以用戶輸入的1和0替換GPIO輸入,並且沒有收到重複的文本。以下是我的代碼的一個子集。任何幫助將不勝感激。

此外,電路明智的,我脫下3,3V PIN 1和返回銷11

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', '[email protected]', 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

這看起來像一個跳躍的問題之前正在運行的是通過一個1K歐姆的電阻。這意味着當門打開或關閉時,在穩定之前,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)