2017-03-03 9 views
0

你好,下午好。我幾乎是編程上的NOOB。我有一個朋友幫我用python腳本,當按下按鈕時,它會打開一個指示燈併發送一封電子郵件。當按鈕按下並保持2秒以上並釋放時,它應該打開併發送一封單獨​​的電子郵件。即使按下按鈕,每次都會發送第一封「正常」電子郵件,但「重要」電子郵件不會發送,但是LED會關閉。 我在Raspberry PI上運行Ubuntu Mate 3 這是腳本的一部分。按下按鈕時,我的python腳本不能完全發送郵件

import RPi.GPIO as GPIO 
import time 
import smtplib 
from email.MIMEMultipart import MIMEMultipart 
from email.MIMEText import MIMEText 
import datetime 



body = "Email message" 
sender = "Room 202 Help" 
subject = "Room 202 Help Button" 
to = "" 
stmpAddress = "smtp.gmail.com" 
username = "" 
password = "" 
normalBody = "Help needed in room 202" 
importantBody = "Request Canceled Room 202" 
ledPin = 23 
buttonPin = 18 
importantPress = 2 #seconds 


GPIO.setmode(GPIO.BCM) 

GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) #makes the pin stay high another words it is set to about 3 volts 
GPIO.setup(ledPin, GPIO.OUT) #makes the pin be an output 

msg = MIMEMultipart() 
msg['From'] = sender 
msg['To'] = to 
msg['Subject'] = subject 
GPIO.output(ledPin,GPIO.LOW) 

while True: 
    buttonPress = GPIO.input(buttonPin) 
    if buttonPress == False: #is the pin low? 
     GPIO.output(ledPin,GPIO.HIGH)#turn on the led 
     print('Button Pressed')#Yes it is low meaning it was shorted to ground 
     buttonPressStart = datetime.datetime.now() #Time the button got pressed 
     while GPIO.input(buttonPin) == False: # while it is still low 
      time.sleep(0.1)#stay here till they let go of the button 
     buttonPressEnd = datetime.datetime.now() # time the button was let go 

     diff = buttonPressEnd - buttonPressStart#the differnce of when the button got pressed and let go, duration on button press 

     if diff > datetime.timedelta(seconds = importantPress): 
      msg.attach(MIMEText(importantBody, 'plain')) 
      GPIO.output(ledPin,GPIO.LOW)#turn off the led if it's on 
      print("Canceling") 
     else: 
      msg.attach(MIMEText(normalBody, 'plain')) 

     server = smtplib.SMTP(stmpAddress, 587) 
     server.starttls() 
     server.login(username, password) 
     server.sendmail(username, to, msg.as_string()) 
     server.quit()#email sent 



    time.sleep(0.01)#sleep a short time so to not eat all resources 

回答

1

去關上發佈the Raspberry Pi forum一個答案,你可以看到一個按鈕是如何長按這樣:

while True: 
    GPIO.wait_for_edge(PIN, GPIO.FALLING) 
    print "Pressed" 
    start = time.time() 
    time.sleep(0.2) 

    while GPIO.input(PIN) == GPIO.LOW: 
     time.sleep(0.01) 
    length = time.time() - start 
    print length